package com.novabluetooth.views;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import com.blankj.utilcode.util.AdaptScreenUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.clj.fastble.BleManager;
import com.clj.fastble.callback.BleGattCallback;
import com.clj.fastble.callback.BleNotifyCallback;
import com.clj.fastble.callback.BleScanCallback;
import com.clj.fastble.callback.BleWriteCallback;
import com.clj.fastble.data.BleDevice;
import com.clj.fastble.exception.BleException;
import com.clj.fastble.scan.BleScanRuleConfig;
import com.clj.fastble.utils.HexUtil;
import com.ebelter.sdks.bean.scale.OfflineMeasureResult;
import com.ebelter.sdks.bean.scale.ScaleMeasureResult;
import com.ebelter.sdks.bean.scale.ScaleUserInfo;
import com.ebelter.sdks.bean.tem.TemMesureResult;
import com.ebelter.sdks.bean.tem.TemMesureResultHis;
import com.ebelter.sdks.enums.ProductStyle;
import com.ebelter.sdks.interfaces.IBlueStationListener;
import com.ebelter.sdks.interfaces.IConnectStationCallback;
import com.ebelter.sdks.interfaces.scale.AIScaleMeasureCallback;
import com.ebelter.sdks.interfaces.tem.ITemMesureResult;
import com.ebelter.sdks.managers.ScaleManager;
import com.ebelter.sdks.managers.TemManager;
import com.ebelter.sdks.utils.LogUtils;
import com.ebelter.sdks.utils.TimeUtils;
import com.empsum.blelibrary.bluetoothutils.BlueToothCallback;
import com.empsum.blelibrary.bluetoothutils.BlueToothUtils;
import com.empsum.blelibrary.bluetoothutils.Data;
import com.empsum.blelibrary.bluetoothutils.StrExchangeBytes;
import com.empsum.blelibrary.bluetoothutils.Utils;
import com.health.model.PopDataBean;
import com.health.tablebean.ARCHIVE_BASEINFO;
import com.health.tools.GlobalConts;
import com.health.viewscontrols.NovaApplication;
import com.health.R;
import com.health.tablebean.BTDevice;
import com.health.tools.SPUtil;
import com.health.widget.PopWindow;
import com.nova.BaseActivity;
import com.nova.view.BaseSharedPreferencesUtil;
import com.nova.view.NovaLog;
import com.novabluetooth.adapter.SBCLMenuGridAdapter;
import com.novabluetooth.data.DeviceShowSaveData;
import com.novabluetooth.data.GlobalContsBlueThooth;
import com.novabluetooth.services.BluetoothConstant;
import com.novabluetooth.services.TJBluetoothLeService;
import com.novabluetooth.services.bean.BluetoothLeDevice;
import com.novabluetooth.services.bean.CDKinfo;
import com.novabluetooth.services.bean.Records;
import com.novabluetooth.services.bluetooth2.ListenService;
import com.novabluetooth.services.constant.BLEConstant;
import com.novabluetooth.services.constant.BluetoolUtil;
import com.novabluetooth.services.enmu.Units;
import com.novabluetooth.services.hqxd.HQXDActivity;
import com.novabluetooth.services.libecg.ecgdemo.MainPC80B;
import com.novabluetooth.services.service.BluetoothLeScannerInterface;
import com.novabluetooth.services.service.BluetoothLeService;
import com.novabluetooth.services.service.BluetoothUtils;
import com.novabluetooth.services.servicedevices.CardioChekService;
import com.novabluetooth.services.servicedevices.NiaoJiht111AHanTangService;
import com.novabluetooth.services.servicedevices.TiWenHtdService;
import com.novabluetooth.services.servicedevices.TiWenJKService;
import com.novabluetooth.services.servicedevices.TiWenNovaService;
import com.novabluetooth.services.servicedevices.TiZhongFatScaleService;
import com.novabluetooth.services.servicedevices.TiZhongNovaService;
import com.novabluetooth.services.servicedevices.TripleService;
import com.novabluetooth.services.servicedevices.XueTangAWXSanNuoService;
import com.novabluetooth.services.servicedevices.XueTangWL1SanNuoService;
import com.novabluetooth.services.servicedevices.XueYaB61TJMRService;
import com.novabluetooth.services.servicedevices.XueYaYuYue760Service;
import com.novabluetooth.services.servicedevices.XueYangKRKService;
import com.novabluetooth.services.servicedevices.XueYangNovaService;
import com.novabluetooth.utils.StringUtils;
import com.novabluetooth.views.iknetbluetoothlibrary.MeasurementResult;
import com.novabluetooth.views.twj.PwBean;
import com.novabluetooth.views.twj.StringUtil;
import com.novabluetooth.views.twj.TwjConstans;
import com.novabluetooth.views.twj.ZHexUtil;
import com.peng.ppscalelibrary.BleManager.Interface.BleDataProtocoInterface;
import com.peng.ppscalelibrary.BleManager.Manager.MyBleManager;
import com.peng.ppscalelibrary.BleManager.Model.BleDeviceModel;
import com.peng.ppscalelibrary.BleManager.Model.BleEnum;
import com.peng.ppscalelibrary.BleManager.Model.BleUserModel;
import com.peng.ppscalelibrary.BleManager.Model.LFPeopleGeneral;
import com.peng.ppscalelibrary.BleManager.util.DataUtil;
import com.peng.ppscalelibrary.BleManager.util.PPUtil;

import android.Manifest;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import javax.security.auth.login.LoginException;

/**
 * 设备测量主界面
 *
 * @author nova
 */
@SuppressLint("NewApi")
public class SBCLActivity extends BaseActivity implements OnClickListener,PopupWindow.OnDismissListener {
    public static int MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION = 1;
    public static String EW = "EW";
    public static String EW_ERRORMSG = "EW_ERRORMSG";
    private static String TAG = "SBCLActivity";
    private GridView gd_view;
    private TextView blueToothState;
    private TextView tv_prompt;
    private ScaleManager mScaleManager;
    private int showNum = 0;
    private com.novabluetooth.views.iknetbluetoothlibrary.BluetoothManager bluetoothManager;
    private TemManager mTemManager;
    /**
     * 卡迪克血脂仪
     */
    public final static UUID UUID_SERVICE =
            UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");//蓝牙设备的Service的UUID --0000ffe0
    public final static UUID UUID_NOTIFY =
            UUID.fromString("0000fff4-0000-1000-8000-00805f9b34fb");//蓝牙设备的Characteristic的UUID --0000ffe1
    public final static UUID UUID_SERVICE_PW =
            UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb");//蓝牙设备的Service的UUID --0000ffe0
    public final static UUID UUID_NOTIFY_PW =
            UUID.fromString("0000fff6-0000-1000-8000-00805f9b34fb");//蓝牙设备的Characteristic的UUID --0000ffe1

    // 测量过程中交互的空间
    private LinearLayout lay_result, lay_celiang;
    private TextView tv_result, tv_state;
    private EditText et_height;
    private Button bt_celiang, bt_cklsjl, bt_bindDevices, btn_back;
    private ImageView show_img;
    String mTypename = "";
    boolean isBlooth2 = false;
    private BlueToothCallback mCallback;
    private BlueToothUtils blueToothUtils;
    private BigDecimal jcresult = new BigDecimal(0l);

    @Override
    public Resources getResources() {
        return AdaptScreenUtils.adaptWidth(super.getResources(), 840);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.bluetooth_sbcl_main);
        BleManager.getInstance().init(getApplication());
        mScaleManager = new ScaleManager(SBCLActivity.this);
        mTemManager=new TemManager(SBCLActivity.this);
        isBlooth2 = SPUtil.getisBlooth2(SBCLActivity.this, false);
        try {
            findViews();
            initData();
            setListeners();
            initBleModular();
            initBluetooth();
            registBroadCast();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initData() {
        bluetoothManager = com.novabluetooth.views.iknetbluetoothlibrary.BluetoothManager.getInstance(this);
        bluetoothManager.initSDK();
        blueToothUtils = BlueToothUtils.getInstance(this,1);
        callBack();
    }

    private final IBlueStationListener mBlueStationListener = new IBlueStationListener() {
        @Override
        public void STATE_OFF() {
            System.out.println("Bluetooth status of mobile phone:Closed");
        }

        @Override
        public void STATE_TURNING_OFF() {
            System.out.println("Bluetooth status of mobile phone:     Closing...");
        }

        @Override
        public void STATE_ON() {
            System.out.println("Bluetooth status of mobile phone:     Open");
        }

        @Override
        public void STATE_TURNING_ON() {
            System.out.println("Bluetooth status of mobile phone:     Opening");
        }
    };

    private void findViews() {
        gd_view = (GridView) findViewById(R.id.gd_view);
        LinearLayout ll_finish = (LinearLayout)findViewById(R.id.ll_finish);
        ll_finish.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        TextView tv_title = (TextView)findViewById(R.id.tv_title);
        tv_title.setText("设备测量");
        findViewById(R.id.bt_save).setVisibility(View.GONE);
        SBCLMenuGridAdapter gdAdapter = new SBCLMenuGridAdapter(SBCLActivity.this);
        gd_view.setAdapter(gdAdapter);
        blueToothState = (TextView) findViewById(R.id.blueToothState);
        lay_result = (LinearLayout) findViewById(R.id.lay_result);
        lay_celiang = (LinearLayout) findViewById(R.id.lay_start);
        tv_prompt=findViewById(R.id.tv_prompt);

        btn_back = (Button) findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);

        tv_result = (TextView) findViewById(R.id.tv_result);
        tv_state = (TextView) findViewById(R.id.tv_state);
        et_height = findViewById(R.id.et_height);

        bt_celiang = (Button) findViewById(R.id.bt_start);
        bt_celiang.setOnClickListener(this);
        bt_cklsjl = (Button) findViewById(R.id.bt_cklsjl);
        bt_bindDevices = (Button) findViewById(R.id.bt_bindDevices);
        bt_cklsjl.setOnClickListener(this);
        bt_bindDevices.setOnClickListener(this);
        show_img = (ImageView) findViewById(R.id.show_img);
    }

    private final ITemMesureResult mITemMesureResult = new ITemMesureResult() {
        @Override
        public void mesureResult(TemMesureResult result) {
            Log.e(TAG,"-----接收到测量结果："+result.toString());
            lay_result.setVisibility(View.VISIBLE);
            lay_celiang.setVisibility(View.VISIBLE);
            // if(TextUtils.isEmpty(mDeviceName)&&isBlooth2){
            // mDeviceName="NOVAEW";
            // }

            cancelProgressDialog();
            DeviceShowSaveData.getDataShow(result.temperature+"", BluetoothConstant.EWENQIANG);

            tv_result.setText("测量结果：\n        " + "体温："+result.temperature+"℃");

            tv_state.setText("获取测量结果成功");
        }

        @Override
        public void mesureHisResult(TemMesureResultHis hisResult) {
            Log.e(TAG,"-----接收到历史测量数据："+hisResult.toString());
        }

        @Override
        public void error(int errorCode,String blueName) {
            Log.e(TAG,"-----接收到error：errorCode="+errorCode);

//            0x01:测量结果温度低，LCD 显示 L
//            0x02:测结果温度高，LCD 显示 H
//            0x03:环境温度过低，LCD 显示 EL
//            0x04:环境温度过高，LCD 显示 EH
//            0x05:低电压，LCD 显示电池符号
//            0x06:其他Err 测量错误，LCD 显示 Err
        }

        @Override
        public void onDevicePoweroff() {
            Log.e(TAG,"-----接收到设备关机");
        }

        @Override
        public void setUnitSuccess() {
            Log.e(TAG,"-----接收到设置单位成功");
        }

        @Override
        public void getHisDataFinish() {
            Log.e(TAG,"-----接收到获取历史数据完成");
        }

        @Override
        public void getVersion(int versionCode) {
            Log.e(TAG,"-----接收到版本号 versionCode="+versionCode);
        }
    };

    private final IConnectStationCallback mConnectStationCallback = new IConnectStationCallback() {
        @Override
        public void onConnected(ProductStyle productStyle, BluetoothDevice device) {
            Log.e("TAG","-----onConnected-----" + device.getName() + "--ScaleAddress=" + device.getAddress());
        }

        @Override
        public void onConnecting(ProductStyle productStyle, BluetoothDevice device) {
            Log.e("TAG","-----onConnecting-----" + device.getName() + "--ScaleAddress=" + device.getAddress());
            Log.e("TAG","Body fat scale connection status:     Connecting " + "\n ScaleName = " + device.getName() + "--ScaleAddress=" + device.getAddress());
        }

        @Override
        public void onDisConnected(ProductStyle productStyle) {
            Log.e("TAG","Body fat scale connection status:     DisConnected");
        }
    };

    private final AIScaleMeasureCallback mAIScaleMeasureCallback = new AIScaleMeasureCallback() {
        @Override
        public void onScaleWake() {
            Log.e("TAG","-----onScaleWake-----Body fat scale wake up");
        }

        @Override
        public void onScaleSleep() {
            Log.e("TAG","-----onScaleSleep-----Body fat scales off screen");

            //Get the user history data at screen time
            ScaleUserInfo userInfo = ScaleUserInfo.getScaleUserInfo();
            requestOffMesureData(userInfo.getUserId(), userInfo.getHeight(), userInfo.getSex(), userInfo.getAge(), userInfo.getRoleType());

        }

        @Override
        public void onReceiveMeasureResult(ScaleMeasureResult result) {


            //接收到测量结果先根据体重判断跟当前使用用户是不是相差2kg，如果相差2kg以内就直接执行下面代码块A1-A2,
            // 如果相差大于2kg应该弹框提示用户此条数据是不是他本人的 如果不是应该把这条数据屏蔽掉 如果是也应该执行下面代码块A1-A2,
            //-------------------------------------------------代码块A1
            if (mScaleManager!=null){
                mScaleManager.updateScaleUserInfo(result.weight,(int) result.getResistance());//这句话的意思是告诉秤这体重和阻抗确定是他的，它底层会做历史记录好判断
            }
            //-------------------------------------------------代码块A2


            try {
                Log.e("TAG","onReceiveMeasureResult-result=" + result);
                lay_result.setVisibility(View.VISIBLE);
                lay_celiang.setVisibility(View.VISIBLE);
                cancelProgressDialog();

                //保存体重
                DeviceShowSaveData.getDataShow(result.getWeight()+"", BluetoothConstant.BEITAITIZHONG);
                tv_result.setText("测量结果：\n        " + "体重："+result.getWeight()+"Kg");
                cancelProgressDialog();
                tv_state.setText("获取测量结果成功");
                Log.e("TAG","-----onReceiveMeasureResult---Received weight data");
            } catch (Exception e) {
                e.printStackTrace();
            }


        }

        @Override
        public void onReceivedynamicMeasureResult(ScaleMeasureResult result) {
            Log.e("TAG","----动态测量---onReceivedynamicMeasureResult-result=" + result);
        }


        @Override
        public void onWeightOverLoad() {
            Log.e("TAG","-----onWeightOverLoad-----Body fat scale overweight warning");
        }

        @Override
        public void onReceiveHistoryRecord(OfflineMeasureResult result) {
            //注意Body Fat-B16的秤没有离线数据  这个方法可以不用复写
            Log.e("TAG","---离线数据--onReceiveHistoryRecord-result = " + result);
            Log.e("TAG","-----onReceiveHistoryRecord-----Body fat scales receive historical data");

        }


        @Override
        public void onHistoryDownloadDone() {
            Log.e("TAG","---离线数据--onHistoryDownloadDone");
        }


        @Override
        public void onLowPower() {
            Log.e("TAG","-----onLowPower-----Low battery indicator on body fat scale");
        }

        @Override
        public void setUserInfoSuccess() {
            Log.e("TAG","-----setUserInfoSuccess-----User information set successfully");
        }

        @Override
        public void receiveTime(long time) {
            Log.e("TAG","-----receiveTime-----The time of receipt of the scale.---time = " + TimeUtils.formatTime1(time));
        }
    };


    private void setListeners() {

        mScaleManager.addBluetoothStationListener(mBlueStationListener);//Add a mobile phone bluetooth status listener
        mScaleManager.setConnectStationCallback(mConnectStationCallback);//Add bluetooth body fat scale connection status listener
        mScaleManager.setScaleMeasureCallback(mAIScaleMeasureCallback);

        mTemManager.addBluetoothStationListener(mBlueStationListener);//Add a mobile phone bluetooth status listener
        mTemManager.setConnectStationCallback(mConnectStationCallback);//Add bluetooth body fat scale connection status listener
        mTemManager.setTemMesureResult(mITemMesureResult);//Add a measurement listening

        mScaleManager.setMustConnectBlueAddress(null);
        mTemManager.setMustConnectBlueAddress(null);
        //-----------04  Set user information
        //Set the user information, and remember to execute once the user information changes
        ScaleUserInfo userInfo = ScaleUserInfo.getScaleUserInfo();

        //Very important note：
        // UserId has a maximum length of 14 characters and must be a character of 0123456789abcdef
        //If there are more than 14 bits, the SDK automatically intercepts the next 14 bits of string

        String userId = "0123456789abcd";
        int sex = 0;                   //0 for boys and 1 for girls
        int height = 168;              //168cm
        int roleType = 0;             //0 for ordinary people and 1 for athletes
        int age = 30;                 //30 years old
        float weight = 50.0f;          //50.5kg For the first time, fill in a value that is similar to your weight
        userInfo.setUserId(userId);
        userInfo.setAge(sex);
        userInfo.setHeight(height);
        userInfo.setRoleType(roleType);
        userInfo.setAge(age);
        userInfo.setWeight(weight);
        mScaleManager.updateUserInfo(userInfo);

        gd_view.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                // BloothTool bloothTool = new BloothTool(MainActivity.this);
                // bloothTool.scanLeDevice(true);
                view.setSelected(true);
                queryIndex = "";
//                if (position == 0) {
//                    queryIndex = BluetoothConstant.TIWEN;
//                    mTypename = BluetoothConstant.TIWEN_TYPENAME;
//
//                } else if (position == 1) {
//
//                    queryIndex = BluetoothConstant.XUEYANG;
//                    mTypename = BluetoothConstant.XUEYANG_TYPENAME;
//
//                } else if (position == 2) {
//                    queryIndex = BluetoothConstant.TRIPLE;
//                    mTypename = BluetoothConstant.TRIPLE_TYPENAME;
//
//                } else if (position == 3){
//
//                    queryIndex = BluetoothConstant.TIZHONGQing2;
//                    mTypename = BluetoothConstant.TIZHONG_TYPENAME2;
//
//                } else if (position == 4) {
//
//                    queryIndex = BluetoothConstant.XUEYA;
//                    mTypename = BluetoothConstant.XUEYA_TYPENAME;
//
//                }else if (position == 5) {
//                    queryIndex = BluetoothConstant.XUETANG;
//                    mTypename = BluetoothConstant.XUETANG_TYPENAME;
//                } else if (position == 6) {
//                    queryIndex = BluetoothConstant.XUEZHI;
//                    mTypename = BluetoothConstant.XUEZHI_TYPENAME;
//                } else if (position == 7) {
//                    queryIndex = BluetoothConstant.TIZHONG;
//                    mTypename = BluetoothConstant.TIZHONG_TYPENAME;
//
//                } else if (position == 8) {
//                    queryIndex = BluetoothConstant.TIZHONGQing;
//                    mTypename = BluetoothConstant.TIZHONG_TYPENAME;
//                } else if (position == 9) {
//                    queryIndex = BluetoothConstant.NIAOCHANGGUI;
//                    mTypename = BluetoothConstant.NIAOCHANGGUI_TYPENAME;
//
//                } else if (position == 10) {
//                    queryIndex = BluetoothConstant.TRIPLE;
//                    mTypename = BluetoothConstant.HB_TYPENAME;
//
//                }else if(position == 11){
//                    queryIndex = BluetoothConstant.ECG;
//                    mTypename = BluetoothConstant.ECG_TYPENAME;
//
//                }else if(position == 12){
//                    queryIndex = BluetoothConstant.EWENQIANG;
//                    mTypename = BluetoothConstant.EWENQIANG_TYPENAME;
//                }else if(position == 13){
//                    queryIndex = BluetoothConstant.MAIBOBO;
//                    mTypename = BluetoothConstant.MAIBOBO_TYPENAME;
//                }

                if (position == 0) {
                    queryIndex = BluetoothConstant.TIWEN;
                    mTypename = BluetoothConstant.TIWEN_TYPENAME;

                } else if (position == 1) {
                    queryIndex = BluetoothConstant.XUEYANG;
                    mTypename = BluetoothConstant.XUEYANG_TYPENAME;
                } else if (position == 2) {
                    queryIndex = BluetoothConstant.BeneCheck;
                    mTypename = BluetoothConstant.TRIPLE_TYPENAME;

                } else if (position == 3){
                    queryIndex = BluetoothConstant.TIZHONGQing2;
                    mTypename = BluetoothConstant.TIZHONG_TYPENAME2;
                } else if (position == 4) {
                    queryIndex = BluetoothConstant.XUEYA;
                    mTypename = BluetoothConstant.XUEYA_TYPENAME;
                }else if (position == 5) {
                    queryIndex = BluetoothConstant.XUETANG;
                    mTypename = BluetoothConstant.XUETANG_TYPENAME;
                }  else if (position == 6) {
                    queryIndex = BluetoothConstant.TIZHONGQing;
                    mTypename = BluetoothConstant.TIZHONG_TYPENAME;
                } else if(position == 7){
                    queryIndex = BluetoothConstant.ECG;
                    mTypename = BluetoothConstant.ECG_TYPENAME;
                }else if(position == 8){
                    queryIndex = BluetoothConstant.EWENQIANG;
                    mTypename = BluetoothConstant.EWENQIANG_TYPENAME;
                }else if(position == 9){
                    queryIndex = BluetoothConstant.MAIBOBO;
                    mTypename = BluetoothConstant.MAIBOBO_TYPENAME;
                }else if (position ==10) {
                    queryIndex = BluetoothConstant.NIAOCHANGGUI_UI;
                    mTypename = BluetoothConstant.NIAOCHANGGUI_TYPENAME;
                }else if(position == 11){
                    queryIndex = TwjConstans.DEVICE_NAME;
                    mTypename = TwjConstans.DEVICE_NAME_TYPENAME;
                }else if(position == 12){
                    queryIndex = BluetoothConstant.PW_01DEVICE_NAME;
                    mTypename = BluetoothConstant.PW_01DEVICE_NAME_TYPENAME;
                }else if(position == 13){
                    queryIndex = BluetoothConstant.TRIPLE;
                    mTypename = BluetoothConstant.TRIPLE_TYPENAME;
                } else if(position == 14){
                    queryIndex = BluetoothConstant.MAIBOBO4;
                    mTypename = BluetoothConstant.MAIBOBO_TYPENAME4;
                }
                Log.e(TAG, "queryIndex: " + queryIndex );
                Log.e(TAG, "mTypename: " + mTypename );
                et_height.setVisibility(View.GONE);
                if (!TextUtils.isEmpty(queryIndex)) {
                    cleanDeviceData();
                    if (BluetoothConstant.NIAOCHANGGUI.equals(queryIndex)) {
//                        tv_state.setText("请先在尿机设备中测量完成后，再点击开始测量。");
//                        tv_prompt.setText("操作提示：1、请先在尿机设备中测量完成；2、点击开始测量");
                        tv_state.setText("尿机开机后，点击开始测量连接设备，设备测量成功自动显示测量结果。");
                        tv_prompt.setText("操作提示：1、把尿机开机；2、点击开始测量，3.设备测量成功自动显示测量结果");
                    } else if (BluetoothConstant.XUETANG.equals(queryIndex)) {
                        tv_prompt.setText("操作提示： 1、请先打开设备；      2、点击开始测量。");
                        tv_state.setText("三诺WL-1型血糖仪若需连续测量，请每次测量间隔   30秒。");
                    } else if ("newTIZHONGQing".equals(queryIndex)) {
                        tv_prompt.setText("操作提示： 1、请先点击开始测量、搜索设备；2、上称(站稳)测量。注意：连续测量需要等屏幕熄灭再次上称测量");
                        tv_state.setText("");
                        tv_state.setText("体脂秤：测试体脂数据需要手动输入身高(单位cm),范围是100-220cm;档案年龄范围是10-99岁");
                        et_height.setVisibility(View.VISIBLE);
                    }else if (BluetoothConstant.XUEYANG.equals(queryIndex)) {
                        tv_prompt.setText("操作提示： 1、请先打开设备；      2、点击开始测量。");
                        tv_state.setText("科瑞康血氧若需连续测量，请每次测量间隔   30秒。");
                    } else if (BluetoothConstant.TIZHONG.equals(queryIndex)) {
                        tv_prompt.setText("操作提示： 1、请先打开设备；      2、点击开始测量。");
                        tv_state.setText("体重秤：请先在体重设备中测量完成后，再点击开始测量；\n" +
                                "脂肪秤：请先点击开始测量，再进行体重测量。");
                    }else if (BluetoothConstant.TIZHONGQing.equals(queryIndex)) {
                        tv_prompt.setText("操作提示： 1、请先打开设备；      2、点击开始测量。");

                        tv_state.setText("体重秤：请先在体重设备中测量完成后，再点击开始测量；\n" +
                                "脂肪秤：请先点击开始测量，再进行体重测量。");
                    } else if (BluetoothConstant.TRIPLE.equals(queryIndex)) {
                        tv_prompt.setText("操作提示： 1、请先打开设备；      2、点击开始测量。");
                        if(BluetoothConstant.TRIPLE_TYPENAME.equals(mTypename)){
                            //百捷三合一
                            tv_state.setText("");
                        }else if(BluetoothConstant.HB_TYPENAME.equals(mTypename)){
                            //血红蛋白
                            tv_state.setText("测量值 < 7g/dL，在设备上显示 Lo；测量值 > 26g/dL，在设备上显示 Hi。");
                        }
                    } else {
                        tv_prompt.setText("操作提示： 1、请先打开设备；      2、点击开始测量。");
                        tv_state.setText("");
                    }
                    bt_cklsjl.setText("查看" + mTypename + "历史数据");
                    // typename = BluetoothConstant.getCLTypeName(queryIndex);
                    // startCLDevice();
                } else {
                    showTextDialog("请先选择测量项目");
                }

            }
        });
    }

    private void scanBle() {
        Log.e(TAG,"开始搜索");
        showProgressDialog("正在搜索百捷三合一");
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceName(true, "BeneCheck")
                .setScanTimeOut(15000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);

        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                // 开始扫描（主线程）
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                // 扫描到一个符合扫描规则的BLE设备（主线程）
                Log.e(TAG,"名称："+bleDevice.getName());
                connectionBle(bleDevice);
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                // 扫描结束，列出所有扫描到的符合扫描规则的BLE设备（主线程）
            }
        });
    }

    private void connectionBle(BleDevice bleDevice) {
        showProgressDialog("正在连接百捷三合一");
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {

            }

            @Override
            public void onConnectSuccess(BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                getNotify(bleDevice);
                blueToothState.setText("蓝牙已连接");
                lay_result.setVisibility(View.VISIBLE);
                tv_state.setText("请等待测量结果");
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                cancelProgressDialog();
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开");
                Log.e(TAG, "onDisConnected: ");
            }
        });
    }

    private void getNotify(BleDevice bleDevice) {
        Log.e(TAG,"getNotify()成功");
        BleManager.getInstance().notify(bleDevice,
                "00001000-0000-1000-8000-00805F9B34FB",
                "00001002-0000-1000-8000-00805F9B34FB",
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {

                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {

                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        try {
                            String formatHexString1 = HexUtil.formatHexString(data);
                            String type = formatHexString1.substring(8, 10);
                            String data1 = formatHexString1.substring(
                                    formatHexString1.length() - 4,
                                    formatHexString1.length() - 2);

                            String data2 = formatHexString1.substring(
                                    formatHexString1.length() - 6,
                                    formatHexString1.length() - 4);
                            int result = hexStringToInt(data1+ data2);
                            switch (type) {
                                case "41":
                                    //血糖
                                    BigDecimal bg = new BigDecimal(result/18.0);
                                    tv_result.setText("血糖测量结果：\n        " + bg.setScale(2, BigDecimal.ROUND_HALF_UP) +"mmol/L");
                                    if (jcresult.compareTo(bg.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
                                        return;
                                    }
                                    jcresult = bg.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    Log.e("xiaoxin","测量结果: "+showNum+"--" + jcresult);
                                    showNum++;
                                    DeviceShowSaveData.getDataShow(jcresult +"", "BeneCheck");
                                    break;
                                case "51":
                                    //尿酸设备
                                    BigDecimal ns = new BigDecimal((result * 0.1)/16.81 * 1000);
                                    tv_result.setText("尿酸测量结果：\n        " + ns.setScale(2, BigDecimal.ROUND_HALF_UP) +"μmol/L");
                                    if (jcresult.compareTo(ns.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
                                        return;
                                    }
                                    jcresult = ns.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    Log.e("xiaoxin","尿酸设备测量结果: "+showNum+"--" + jcresult);
                                    DeviceShowSaveData.getDataShow(jcresult +"", "BeneCheck-ns");
                                    break;
                                case "61":
                                    //胆固醇设备
                                    BigDecimal dgc = new BigDecimal(result/38.66);
                                    tv_result.setText("胆固醇测量结果：\n        " + dgc.setScale(2, BigDecimal.ROUND_HALF_UP) +"mmol/L");
                                    if (jcresult.compareTo(dgc.setScale(2, BigDecimal.ROUND_HALF_UP)) == 0) {
                                        return;
                                    }
                                    jcresult = dgc.setScale(2, BigDecimal.ROUND_HALF_UP);
                                    Log.e("xiaoxin","胆固醇设备测量结果: "+showNum+"--" + jcresult);
                                    DeviceShowSaveData.getDataShow(jcresult +"", "BeneCheck-dgc");
                                    break;
                            }
                            lay_result.setVisibility(View.VISIBLE);
                            tv_state.setText("获取测量结果成功");
                            if(showNum == 5){
                                showNum = 0;
                            }
                            Timer timer = new Timer();
                            timer.schedule(new TimerTask() {
                                @Override
                                public void run() {
                                    showNum = 0;
                                }
                            },10000);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    public static int hexStringToInt(String HexString) {

        int inJTFingerLockAddress = Integer.valueOf(HexString, 16);

        return inJTFingerLockAddress;
    }

    private void callBack() {
        mCallback = new BlueToothCallback() {
            //连接 状态
            @Override
            public void onStateCallBack(int state) {
                switch (state){
                    case BluetoothGatt.STATE_CONNECTED:
                        //成功
                        ToastUtils.showShort("连接成功");
                        byte[] uih = StrExchangeBytes.hexStringToBytes("UIH");
                        sendData(uih);
                        break;
                    case BluetoothGatt.STATE_DISCONNECTED:
                        //失败
                        ToastUtils.showShort("连接失败");
                        break;
                }
            }

            //搜索到设备
            @Override
            public void onFindDevice(BluetoothDevice device) {
                Log.e(TAG, "onFindDevice: "+device.getName() );
                if (device!=null && BluetoothConstant.NIAOCHANGGUI_UI.equals(device.getName())) {
                    blueToothUtils.connDevice(device.getAddress());
                }
            }

            //打开通知状态回调
            @Override
            public void onNotifyState(boolean onNotifyState) {
                if (!onNotifyState) {
                    ToastUtils.showShort("开启通知服务失败");
                }
            }

            @Override
            public void onFinishFind() {
            }
            @Override
            public void onDataCallBack(byte[] bytes) {
                //尿机数据回调
//                myData.setText(StrExchangeBytes.bytesToHexString(bytes));
                Log.e("xiaoxin", "onDataCallBack: " +
                        StrExchangeBytes.bytesToHexString(bytes) );
                Data data = Utils.parserOneData(bytes);
                if (data != null) {
                    String ubg = data.getUBGValue() + "(" + data.getUBG() + ")";
                    String bld = data.getBLDValue() + "(" + data.getBLD() + ")";
                    String bil = data.getBILValue() + "(" + data.getBIL() + ")";
                    String ket = data.getKETValue() + "(" + data.getKET() + ")";
                    String glu = data.getGLUValue() + "(" + data.getGLU() + ")";
                    String pro = data.getPROValue() + "(" + data.getPRO() + ")";
                    String ph  = data.getPH() ;
                    String nit = data.getNITValue() + "(" + data.getNIT() + ")";
                    String leu = data.getLEUValue() + "(" + data.getLEU() + ")";
                    String sg  = data.getSG();
                    String vc  = data.getVCValue() + "(" + data.getVC() + ")";
                    DeviceShowSaveData.getNiaoYeBLE_EMP_UI(ubg,bld,bil,ket,glu,pro,ph,nit,leu,sg,vc);
                    final StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(
                            "测量结果:\n"
                            + "尿胆原:" +  ubg
                            + "  潜血:"  + bld
                            + "  胆红素:" + bil
                            + "  酮体:" + ket
                            + "  葡萄糖:" + glu
                            + "  蛋白质:" + pro
                            + "  PH:" + ph
                            + "  亚硝酸盐:" + nit
                            + "  白细胞:" + leu
                            + "  比重:" + sg
                            + "  维生素:" + vc
                    );
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Log.e(TAG, "run: " + stringBuilder.toString());
                            tv_state.setText(stringBuilder.toString());
                            tv_result.setText(stringBuilder.toString());
                        }
                    });

                }
            }

            //心率带数据回调
            @Override
            public void heartDataReceived(byte[] bytes) {
//                myData.setText(StrExchangeBytes.bytesToHexString(bytes));
            }
            @Override
            public void batteryDataReceived(byte[] bytes) {
//                myData.setText(StrExchangeBytes.bytesToHexString(bytes));
            }

        };

        blueToothUtils.setCallback(mCallback);
    }

    private void sendData(byte[] data){
       blueToothUtils.sendData(data);
    }

    /**
     * 扫码倍泰体脂秤
     */
    private void scanBeiTaiBle() {
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceName(true, "eBody-Fat-Scale")
                .setScanTimeOut(12000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                showProgressDialog("正在搜索倍泰体脂秤设备");
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                connBeiTaiBle(bleDevice);
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
            }
        });
    }

    private void connBeiTaiBle(BleDevice bleDevice) {

        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                showProgressDialog("开始连接体脂秤设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                ToastUtils.showShort("连接失败" + exception.toString());
                blueToothState.setText("连接失败");
                tv_state.setText("蓝牙连接失败请重新连接：\n        " + exception.toString());
                cancelProgressDialog();
                Log.e(TAG, "onConnectFail: " +  exception.toString());
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " );
                showProgressDialog("设备已连接");
                blueToothState.setText("蓝牙已连接");
                tv_state.setText("蓝牙已连接：\n        " + "等待返回结果");
                cancelProgressDialog();
                getBeiTaiNotify(bleDevice);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                ToastUtils.showShort("已断开连接");
                blueToothState.setText("蓝牙已断开");
//                tv_state.setText("蓝牙已断开：\n        " + "请重新测量");
            }
        });
    }

    private void getBeiTaiNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                "0000fff0-0000-1000-8000-00805f9b34fb",
                "0000fff4-0000-1000-8000-00805f9b34fb",
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
                        if (data.length > 4) {
                            writeBeiTaiSignaling(bleDevice);
                            String substring = hexString.substring(3, 6);
                            int dd = Integer.parseInt(substring, 16);
                            Double weight = (double) dd / 10;
                            Log.e(TAG, "测量结果: "+ weight );
                            DeviceShowSaveData.getDataShow(weight + "", BluetoothConstant.BEITAITIZHONG);
                            tv_result.setText("测量结果：\n        " + "体重：" + weight + "Kg");
                            tv_state.setText("测量结果：\n        " + "体重：" + weight + "Kg");
                            cancelProgressDialog();
//                            tv_state.setText("获取测量结果成功");
                        }
                    }
                });
    }

    //发送关机数据
    private void writeBeiTaiSignaling(BleDevice bleDevice) {
        //0xFD 0x31 关机信令
        byte[] bytes = StringUtils.hexStringToByteArray("FD31");
        BleManager.getInstance().write(bleDevice, "0000fff0-0000-1000-8000-00805f9b34fb",
                "0000fff3-0000-1000-8000-00805f9b34fb", bytes, new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        Log.e(TAG, "beitai onWriteSuccess: " );
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        Log.e(TAG, " beitaionWriteFailure: "+exception.toString() );
                    }
                });
    }

    @Override
    public void onClick(View v) {
        try {
            int id = v.getId();
            if (id == R.id.btn_back) {
                SBCLActivity.this.finish();
            } else if (id == R.id.bt_start) {
                // 开始测量
                LogUtils.e(TAG,"queryIndex  " + queryIndex);

                if (BluetoothConstant.MAIBOBO4.equals(queryIndex)) {
                    blueToothState.setText("蓝牙已打开");
                    showProgressDialog("正在搜索脉搏波4.0设备");
                    scanMaiboboBle();
                    LogUtils.e(TAG,"正在搜索脉搏波4.0设备");
                    return;
                }

                if (BluetoothConstant.BeneCheck.equals(queryIndex)) {
                    scanBle();
                    LogUtils.e(TAG,"开始搜索蓝牙：新版本百捷三合一");
                    return;
                }

                if(queryIndex.equals(TwjConstans.DEVICE_NAME)){
                    sacnTwjBle();
                    LogUtils.e(TAG,"开始搜索蓝牙：体温计");
                    return;
                }

                if(queryIndex.equals(BluetoothConstant.PW_01DEVICE_NAME)){
                    sacnPWBle();
                    LogUtils.e(TAG,"开始搜索蓝牙：pw-01");
                    return;
                }

                if(queryIndex.equals(BluetoothConstant.NIAOCHANGGUI_UI)){
                    blueToothUtils.scanDevice();
                    LogUtils.e(TAG,"开始搜索蓝牙：体脂秤");
                    return;
                }
                if(queryIndex.equals(BluetoothConstant.TIZHONGQing)){
//                    startWork();
                    scanBeiTaiBle();
                    LogUtils.e(TAG,"开始搜索蓝牙：体脂秤");
                    return;
                }
                if(BluetoothConstant.EWENQIANG.equals(queryIndex)){
                    startWork2();
                    return;
                }
                if(queryIndex.equals(BluetoothConstant.MAIBOBO)){
                    setBluetooth();
                    dealStopMeasureBtn();
                    return;
                }
                if (!TextUtils.isEmpty(queryIndex)) {
                    if ("newTIZHONGQing".equals(queryIndex)) {
//                        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
//                                "name ="+"'轻加脂肪秤'");
//                        if(btDevices.size() == 0){
//                            ToastUtils.showShort("请先绑定轻+设备");
//                            return;
//                        }
//                        String name = btDevices.get(0).getName();
//                        String mustConnectAddress = btDevices.get(0).getMacAddress();
//                        if (!TextUtils.isEmpty(mustConnectAddress)) {
//                            scanDevice(mustConnectAddress);
//                        }else {
//                            ToastUtils.showShort("请先绑定轻+设备");
//                        }
                        bindingDevice();
                    }else {
                        startCLDevice();
                        if (!queryIndex.equals("XUEYANG")) {
//                            if ("BeneCheck".equals(queryIndex)) {
//                                scanBle();
//                            }
                        }
                    }
                } else {
                    showTextDialog("请先选择测量项目");
                }
            } else if (id == R.id.bt_bindDevices) {
                // 绑定设备
                Intent intent = new Intent(SBCLActivity.this, BluetoothDeviceBindActivity2.class);
                startActivity(intent);
            } else if (id == R.id.bt_cklsjl) {
                isFind = false;
                // 查看历史数据
                ckCLHistoryData();
            } else {
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 查看历史记录
     *
     * @author 王婷婷
     * @date 2017年7月14日 下午2:33:48
     */
    private void ckCLHistoryData() {
        String typename = BluetoothConstant.getCLTypeName(queryIndex);
        if (TextUtils.isEmpty(typename)) {
            showTextDialog("请先选择测量项目");
        } else {
            Intent intent2;
            if ("newTIZHONGQing".equals(queryIndex)) {
                intent2 = new Intent(SBCLActivity.this, ExamHistoryWeightActivity.class);
            } else {
                intent2 = new Intent(SBCLActivity.this, ExamHistoryActivity.class);
            }
            Log.e(TAG, "ckCLHistoryData:queryIndex   " +  queryIndex);
            Log.e(TAG, "ckCLHistoryData:queryIndex   " +  mTypename);
            if(BluetoothConstant.TRIPLE.equals(queryIndex)){
                //百捷设备需要 区分 三合一设备 还是 血红蛋白【两种展示测量历史记录 的 方式不一样】
                if(BluetoothConstant.HB_TYPENAME.equals(mTypename)){
                    intent2.putExtra("flag", BluetoothConstant.HB_TYPENAME);
                }else{
                    intent2.putExtra("flag", typename);
                }
            }else{
                intent2.putExtra("flag", typename);
            }
            startActivity(intent2);
        }

    }

    /***
     * 清空数据
     *
     * @author 王婷婷
     * @date 2017年7月14日 下午2:34:23
     */
    private void cleanDeviceData() {
        lay_result.setVisibility(View.GONE);
        tv_state.setText("");
        tv_result.setText("");
        show_img.setVisibility(View.GONE);

        // closeAndExit();
    }

    // --------------------注册心电-----------------------------------------------------
    MsgReceiver msgReceiver;

    /**
     * 注册服务广播
     *
     * @author 王婷婷
     * @date 2015年12月18日 上午11:18:47
     */
    private void registBroadCast() {
        // 动态注册广播接收器
        msgReceiver = new MsgReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothConstant.REGISTER_GB);
        intentFilter.addAction(BluetoothConstant.REGISTER_EW);
        intentFilter.addAction(BluetoothConstant.REGISTER_Waiting);
        System.out.println("广播已注册");
        registerReceiver(msgReceiver, intentFilter);

    }

    /**
     * 广播接收器
     *
     * @author len Yuwell BloodPressure可以关闭蓝牙了
     */
    public class MsgReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, final Intent intent) {
            if (BluetoothConstant.REGISTER_GB.equals(intent.getAction())) {
                // 拿到进度，更新UI
                try {
                    Log.e(TAG, "MsgReceiver 广播接收器");
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                            initEcgJpg(intent);
                            // stopService(new Intent(SBCLActivity.this,
                            // ListenService.class));
                        }
                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else if (BluetoothConstant.REGISTER_EW.equals(intent.getAction())) {
                String ewValue = intent.getBundleExtra("ewValue").getFloat(SBCLActivity.EW) + "";
                mDeviceName = "NOVAEW";
                if (TextUtils.isEmpty(ewValue)) {
                    String ewValue_errorMsg = intent.getBundleExtra("ewValue").getString(SBCLActivity.EW_ERRORMSG) + "";
                    if (!TextUtils.isEmpty(ewValue_errorMsg)) {
                        tv_state.setText(ewValue_errorMsg + "，请重新测量！");
                    }
                } else {
                    showData(ewValue);
                }

            } else if (BluetoothConstant.REGISTER_Waiting.equals(intent.getAction())) {
                showProgressDialog("等待接收数据");
            }

        }
    }

    public void requestOffMesureData(String userId, int height, int sex, int age, int roleType) {
        if (mScaleManager != null && mScaleManager.isConnected()) {
            mScaleManager.requestOffMesureData(userId, height, sex, age, roleType);
        }
    }

    // --------------------------------蓝牙数据处理-------------------------------------------
    private int statTZ = -1;
    private void startWork() {

        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                "name ="+"'倍泰体脂秤'");
        if(btDevices.size() == 0){
            return;
        }
        String name = btDevices.get(0).getName();

        String mustConnectAddress = btDevices.get(0).getMacAddress();
        if (!TextUtils.isEmpty(mustConnectAddress)) {
            mScaleManager.setMustConnectBlueAddress(mustConnectAddress);
        }
        //-----------05
        mScaleManager.startWork();

        showProgressDialog("正在搜索体脂秤设备");
        Log.e(TAG,"绑定设备名："+name);
//        if (btDevices.size() > 0) {
//            // if (btDevices.get(0).isVersion4()) {
//            mDeviceName = device.getName();
//            NovaLog.e(TAG, device.getName());
//            BaseSharedPreferencesUtil.saveStr(mContext, "nova_debug", "deviceName", device.getName());
//
//            bindDeviceData(device);
//            // }
//        }

        // mScaleManager.startWork();//The engine started working
        // mScaleManager.stopWork();//The engine stop working
    }

    private void startWork2() {
        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                "name ="+"'倍泰额温枪'");
        if(btDevices.size() == 0){
            return;
        }
        String name = btDevices.get(0).getName();

        String mustConnectAddress = btDevices.get(0).getMacAddress();
        if (!TextUtils.isEmpty(mustConnectAddress)){
            mTemManager.setMustConnectBlueAddress(mustConnectAddress);
        }
        //-----------05
        mTemManager.startWork();

        showProgressDialog("正在搜索额温枪设备");
        Log.e(TAG,"绑定额温枪："+name);

        // mScaleManager.startWork();//The engine started working
        // mScaleManager.stopWork();//The engine stop working
    }

    private void scanDevice(String macAddress) {
        BleManager.getInstance().init(getApplication());
        showProgressDialog("正在搜索体脂秤设备");
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(macAddress)
                .setScanTimeOut(10000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
                // 开始扫描（主线程）
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                // 扫描到一个符合扫描规则的BLE设备（主线程）
                connectionTzBle(bleDevice);
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                // 扫描结束，列出所有扫描到的符合扫描规则的BLE设备（主线程）
            }
        });
    }

    private void connectionTzBle(BleDevice bleDevice) {

        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                showProgressDialog("开始连接体脂秤设备");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                showProgressDialog("连接失败 超时");
                cancelProgressDialog();
                Toast.makeText(SBCLActivity.this,"连接失败 超时",Toast.LENGTH_SHORT).show();
                Log.e(TAG, "onConnectFail: " +  exception.toString());
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                mDeviceName = "Health Scale";
//                mDeviceName = "HeartRate Scale";
                Log.e(TAG, "onConnectSuccess: " );
                showProgressDialog("连接成功");
                getTzNotify(bleDevice);

                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        writeTzData(bleDevice);
                    }
                },200);

            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                cancelProgressDialog();
                Toast.makeText(SBCLActivity.this,"已断开连接",Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void getTzNotify(BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                "0000fff0-0000-1000-8000-00805f9b34fb",
                "0000fff4-0000-1000-8000-00805f9b34fb",
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        try {
                            cancelProgressDialog();
                            Log.e(TAG, "onCharacteristicChanged: "+data );
                            String hexString = StringUtils.bytes2HexString(data);
//                            Records result = BleHelper.getInstance().parseDLScaleMeaage2(data);
//                            Records records = BleHelper.getInstance().parseScaleData(SBCLActivity.this,
//                                    hexString, 170f, 1, 26, 0);
//                            Log.e(TAG, "onCharacteristicChanged: " + records.toString());
//
//                            if (result != null) {
//                                Log.e(TAG,"体脂数据  " + result.toString());
//                                showData(result.getRweight() + "");
//                                cancelProgressDialog();
//                                BleManager.getInstance().cancelScan();
//                                BleManager.getInstance().disconnectAllDevice();
//                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    private void writeTzData(BleDevice bleDevice) {
//        String sendData = BleHelper.getInstance().assemblyAliData(Units.UNIT_KG.getCode(), "01");
//        final byte[] dataArray = StringUtils.hexStringToByteArray(sendData);
//        BleManager.getInstance().write(bleDevice,
//                "0000fff0-0000-1000-8000-00805f9b34fb",
//                "0000fff1-0000-1000-8000-00805f9b34fb", dataArray, new BleWriteCallback() {
//                    @Override
//                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
//                        Log.e(TAG, "onWriteSuccess: " );
//                        showProgressDialog("已连接：写入数据成功 等待体重秤返回结果");
//                    }
//
//                    @Override
//                    public void onWriteFailure(BleException exception) {
//                        Log.e(TAG, "onWriteFailure: "+exception.toString() );
//                    }
//                });
    }

    /**
     * 蓝牙处理
     *
     * @author 王婷婷
     * @date 2017年7月14日 上午11:54:45
     */
    private void startCLDevice() {
        cleanDeviceData();

        if(BluetoothConstant.TIZHONGQing2.equals(queryIndex)){
            statTZ = 0 ;
            Log.e(TAG, "startCLDevice: TIZHONGQing2" );
            //体重测量
            startTZ();
        }
        if(BluetoothConstant.TIZHONGQing.equals(queryIndex)){
            statTZ = 0 ;
            //体重测量
//            startTZ();
            Log.e(TAG, "startCLDevice: TIZHONGQing" );
            ScaleUserInfo userInfo = ScaleUserInfo.getScaleUserInfo();
            requestOffMesureData(userInfo.getUserId(), userInfo.getHeight(), userInfo.getSex(), userInfo.getAge(), userInfo.getRoleType());
        }else if(BluetoothConstant.XUEZHI.equals(queryIndex)){
            //卡迪克血脂仪 ss
            setListeners();
            initBleModular();
            initBluetooth();
            scanLeDevice(true);

//            isBlooth2 = SPUtil.getisBlooth2(SBCLActivity.this, false);
//            setListeners();
//            initBleModular();
//            initBluetooth();
//            isScanning = false;
//            isReData = 0 ;

            //开始扫描
//            scanDevice();
        } else {
            Log.e(TAG, "isBlooth2：" + isBlooth2);
            if (BluetoothConstant.ECG.equals(queryIndex)) {
                bt_cklsjl.setText("查看心电历史数据");
                // 心电
                initPopDatas();
                onPopwindowOptions();


            } else {

                if (BluetoothConstant.TIWEN.equals(queryIndex)) {
                    // 体温
                    if (isBlooth2) {
                        initBluetooth2();
                    } else {
                        initBleModular();
                        initBluetooth();
                        scanLeDevice(true);
                    }

                } else {//不是心电和体温走
                    initBleModular();
                    initBluetooth();
                    scanLeDevice(true);

                }

            }
        }


    }
    private boolean isScanning = false;
//    private BluetoothAdapter mAdapter;
    private BluetoothGatt mBluetoothGatt;

    /**
     * 断开连接
     */
    public void disconnect() {

        if (null == mBluetoothGatt) {
            return;
        }
        mBluetoothGatt.disconnect();
        mBluetoothGatt.close();
        mBluetoothGatt = null;

    }
    @SuppressLint("HandlerLeak")
    Handler handler2 = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            if(msg.what==0){
                CDKinfo data = (CDKinfo)msg.obj;
                if(data.getIsReData()==0&&data.getStute()==0){
                    String type = data.getType();
                    showData(type);
                }
            }
        }
    };

    public boolean isbind = false;
    public boolean isFind = false;
    private BluetoothUtils mBluetoothUtils;
    private Handler scanHandler;
    private BluetoothLeScannerInterface mScanner;
    protected static final int REQUEST_ACCESS_COARSE_LOCATION_PERMISSION = 101;
    //测量体重走的方法
    private void startTZ(){
        mDeviceName = "";
        mDeviceAddress = "";
        Log.e("mtypename=",mTypename+"");
        showProgressDialog("正在搜索" + mTypename + "设备");
        isFind = true;
        preferences = mContext.getSharedPreferences("nova_debug", Context.MODE_PRIVATE);
        editor = preferences.edit();
        // initBleModular();
//        mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());

        //判断是否支持蓝牙
        mBluetoothUtils = new BluetoothUtils(SBCLActivity.this);
        if (mBluetoothUtils.isBluetoothLeSupported()&&isFind) {

            scanHandler = new Handler();
            //获取扫描对象
            mScanner = mBluetoothUtils.initBleScaner(nofityHandler);
            //注册通知
//            mContext.registerReceiver(mGattUpdateReceiver, BluetoothUtils.makeGattUpdateIntentFilter());
            //绑定蓝牙服务服务
            final Intent gattServiceIntent = new Intent(SBCLActivity.this, BluetoothLeService.class);
            bindService(gattServiceIntent, mServiceConnection2, BIND_AUTO_CREATE);
            isbind = true;
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && ContextCompat.checkSelfPermission(SBCLActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION)
                    != PackageManager.PERMISSION_GRANTED) {
                requestPermission(Manifest.permission.ACCESS_COARSE_LOCATION,
                        getString(R.string.permission_blurtooth),
                        REQUEST_ACCESS_COARSE_LOCATION_PERMISSION);
            } else {
                //启动扫描
                scanHandler.post(scanThread);

            }

        } else {
            blueToothState.setText("该PAD不支持蓝牙4.0");
            finish();
        }
        isRegisterReceiver = true;
    }
    /**
     * 扫描线程
     */
    private Runnable scanThread = new Runnable() {

        public void run() {
            // 你的线程所干的事情
            startScan();
            //十秒后再重复工作
            scanHandler.postDelayed(scanThread, 15000);
        }
    };
    /**
     * 开始扫描蓝牙
     */
    private void startScan() {
        mBluetoothUtils.askUserToEnableBluetoothIfNeeded();
//        if (mIsBluetoothOn && mIsBluetoothLePresent && mActivty) {//页面激活的状态下才真正扫描
        if(isFind){
            mScanner.scanLeDevice(8000, true);
        }
            //invalidateOptionsMenu();
//        }
    }
    /**
     * Find bluetooth notification interface corresponding
     */
    Handler nofityHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case BluetoolUtil.FOUND_DEVICE:
                    Log.i(TAG, "[Ble startus num ]==" + (null == mBuletoothLeService2 ? "no init " : mBuletoothLeService2.getmConnectionState()));
                    BluetoothLeDevice deviceLe = (BluetoothLeDevice) msg.obj;

                    if (null != deviceLe && null != mBuletoothLeService2 && mBuletoothLeService2.getmConnectionState() == BluetoothLeService.STATE_DISCONNECTED) {
                        mDeviceAddress = deviceLe.getAddress();
                        mDeviceName = deviceLe.getName();
//                        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
//                                "macAddress = " + "'" + mDeviceAddress + "'");
//                        if(btDevices.size()>0){
                            BaseSharedPreferencesUtil.saveStr(mContext, "nova_debug", "deviceName", mDeviceName);
                            editor.putString("deviceName", mDeviceName);
                            editor.commit();
                            Log.e("mDeviceAddress--",mDeviceAddress+"handler---");
                            Log.e("mDeviceName--",mDeviceName);
                            if (!TextUtils.isEmpty(mDeviceAddress))
                                mBuletoothLeService2.connect(mDeviceAddress);
//                        }else{
//                            scanHandler.post(scanThread);
//                        }
                    }
                    break;

                case BluetoolUtil.RECEIVE_DATA: //接收到数据
//                    String data = (String) msg.obj;
//                    Log.e("---data--",data);
//                    Records records = null;
//                    if (data.startsWith("cf") || data.startsWith("ce")) {
//                        records = BleHelper.getInstance().parseDLScaleMeaage2(SBCLActivity.this, data);
//                        Log.e("records:",records.getRweight()+"");
//                    } else if (data.startsWith("0306")) {
//                        records = BleHelper.getInstance().parseScaleData(SBCLActivity.this, data, 170f, 1, 26, 0);
//                    }
//                    if (null != records) {
//                        String data2 = records.getRweight()+"";
//                        showData(data2);
//                        cancelProgressDialog();
//                    }
                    break;
            }
            super.handleMessage(msg);

        }
    };
    /**
     * 请求权限
     * <p>
     * 如果权限被拒绝过，则提示用户需要权限
     */
    @TargetApi(23)
    protected void requestPermission(final String permission, String rationale, final int requestCode) {
        if (shouldShowRequestPermissionRationale(permission)) {
            showAlertDialog(getString(R.string.permission_title_rationale), rationale,
                    new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            requestPermissions(new String[]{permission}, requestCode);
                        }
                    }, getString(R.string.ok_btn), null, getString(R.string.cancle_btn));
        } else {
            requestPermissions(new String[]{permission}, requestCode);
        }
    }
    private AlertDialog mAlertDialog;

    /**
     * 显示指定标题和信息的对话框
     *
     * @param title                         - 标题
     * @param message                       - 信息
     * @param onPositiveButtonClickListener - 肯定按钮监听
     * @param positiveText                  - 肯定按钮信息
     * @param onNegativeButtonClickListener - 否定按钮监听
     * @param negativeText                  - 否定按钮信息
     */
    protected void showAlertDialog(@Nullable String title, @Nullable String message,
                                   @Nullable DialogInterface.OnClickListener onPositiveButtonClickListener,
                                   @NonNull String positiveText,
                                   @Nullable DialogInterface.OnClickListener onNegativeButtonClickListener,
                                   @NonNull String negativeText) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton(positiveText, onPositiveButtonClickListener);
        builder.setNegativeButton(negativeText, onNegativeButtonClickListener);
        mAlertDialog = builder.show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_ACCESS_COARSE_LOCATION_PERMISSION:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (null != mAlertDialog) mAlertDialog.dismiss();
                    if(isFind){
                        //启动扫描
                        scanHandler.post(scanThread);
//                        scanThread.
                    }
                }
                break;

            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }

    BluetoothAdapter mBluetoothAdapter;// ble
    BluetoothManager mBluetoothManager;
    // private BluetoothAdapter mBluetoothAdapter2;// 蓝牙2.0
    public SharedPreferences preferences;
    public SharedPreferences.Editor editor;
    private Intent intent = new Intent("com.example.communication.RECEIVER");

    public final String DEVICE_NAME = "device_name";
    public final String GET_VALUE = "getValue";
    public final String TOAST = "toast";
    public final int MESSAGE_STATE_CHANGE = 1;
    public final int MESSAGE_READ = 2;
    public final int MESSAGE_WRITE = 3;
    public final int MESSAGE_DEVICE_NAME = 4;
    public final int MESSAGE_TOAST = 5;

    public boolean ifState = false;
    TJBluetoothLeService mBluetoothLeService;
    BluetoothLeService mBuletoothLeService2;
    String mDeviceAddress;
    String mDeviceName;
    Date date_pre_yyxyj = null;// 鱼跃血压计
    Date date_pre_krkxy = null;// 科瑞康血氧
    Date date_pre_htdewq = null;// 和泰达耳温枪
    // Handler mHandler = new Handler();
    boolean mScanning, isReceive;
    // Stops scanning after 10 seconds.
    private boolean isRegisterReceiver = false;
    private boolean isBound = false;
    private String queryIndex;

    private void initBluetooth() {

        Log.w("eeeeeeeeeeeeee----", "设备服务---开启");
        preferences = mContext.getSharedPreferences("nova_debug", Context.MODE_PRIVATE);
        editor = preferences.edit();
//         initBleModular();
        try {
            mContext.registerReceiver(mGattUpdateReceiver, makeGattUpdateIntentFilter());
        } catch (Exception e) {
            e.printStackTrace();
        }

        isRegisterReceiver = true;
    }

    /**
     * 初始化蓝牙信息
     *
     * @author 王婷婷
     * @date 2017年7月12日 下午2:49:29
     */
    @SuppressLint("NewApi")
    private void initBleModular() {
//        isScanning = false;

        if (!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)) {
            blueToothState.setText("该PAD不支持蓝牙4.0");
            return;
        }

        mBluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
        mBluetoothAdapter = mBluetoothManager.getAdapter();

        // Checks if Bluetooth is supported on the device.
        if (mBluetoothAdapter == null) {
            blueToothState.setText("该PAD不支持蓝牙");
            return;
        }

        // TODO 开启蓝牙，开始测量
        if (!mBluetoothAdapter.isEnabled()) {
            boolean flag = mBluetoothAdapter.enable();
            // 开启蓝牙成功还是失败
            if (flag) {
                blueToothState.setText("蓝牙已打开");
            } else {
                blueToothState.setText("自动开启蓝牙失败，请在【系统设置】--【蓝牙】手动开启蓝牙");
            }

        } else {
            blueToothState.setText("蓝牙已打开");
        }

    }

    private Handler mHandler = new Handler();
    // Stops scanning after 10 seconds.
    private static final long SCAN_PERIOD = 10000;

    /**
     * 进行蓝牙设备的扫描
     *
     * @param enable
     * @author 王婷婷
     * @date 2017年7月12日 下午2:50:10
     */
    private void scanLeDevice(final boolean enable) {

        if (enable) {
            // Stops scanning after a pre-defined scan period.
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    if (mScanning) {
                        cancelProgressDialog();
                        lay_celiang.setVisibility(View.VISIBLE);
                        mScanning = false;
                        mBluetoothAdapter.stopLeScan(mLeScanCallback);
                    }
                }
            }, SCAN_PERIOD);
            if (!TextUtils.isEmpty(mTypename)) {
                showProgressDialog("正在搜索" + mTypename + "设备");
            } else {
                showProgressDialog("正在搜索设备");
            }

            mScanning = true;
            mBluetoothAdapter.startLeScan(mLeScanCallback);
        } else {
            cancelProgressDialog();
            if (mScanning) {
                lay_celiang.setVisibility(View.VISIBLE);
            }
            mScanning = false;
            mBluetoothAdapter.stopLeScan(mLeScanCallback);
            // showTextDialog("未搜索到" + typename + "设备");
        }
    }

    // Device scan callback.
    private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {

        @Override
        public void onLeScan(final BluetoothDevice device, int rssi, byte[] scanRecord) {
            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    Log.e("QueryIndex", "QueryIndex" + "=======" + queryIndex);
                    Log.e("device.getName()", "device.getName()" + "=======" + device.getName()+"77");

                    if (!TextUtils.isEmpty(device.getName())) {
                        if (TextUtils.isEmpty(queryIndex)) {
                            return;
                        }
                        Log.e(TAG, device.getName() + "\n" + queryIndex);
                        switch (queryIndex) {
                            case BluetoothConstant.XUEZHI:
                                if (!BluetoothConstant.XUEZHI_CARDIOCHEK.equals(device.getName())) {
                                    return;
                                }
                                break;
                            case BluetoothConstant.TIZHONG:
                                if (!BluetoothConstant.TIZHONG_NOVA.equals(device.getName())
                                       && !BluetoothConstant.TIZHONG_FATSCALE.equals(device.getName())) {//增加模块
                                    return;
                                }
                                break;
                            case BluetoothConstant.TIZHONGQing:
                                String currentName2 = "";
                                if(device.getName().length() > 5){
                                    String subName = device.getName().substring(0, 5);
                                    Log.e("TAG","获取前九位："+subName);
                                    if(subName.contains("Body")){
                                        currentName2 = device.getName();
                                    }
                                }
                                if (currentName2.equals("")) {//增加模块
                                    return;
                                }
                                break;
                            case BluetoothConstant.TIZHONGQing2:
                                if (!BluetoothConstant.TIZHONG_HEALTH.equals(device.getName())) {//增加模块
                                    return;
                                }
                                break;
                            case BluetoothConstant.TIWEN:
                                if (!BluetoothConstant.TIWEN_EWQ_NOVA.equals(device.getName())
                                        && !BluetoothConstant.TIWEN_EWQ_HTD.equals(device.getName())
                                        && !BluetoothConstant.TIWEN_EWENQ_HTD.equals(device.getName())
                                        && !BluetoothConstant.TW_JK.equals(device.getName())&&!BluetoothConstant.TIWEN_EWENQ_HTD3.equals(device.getName())) {
                                    return;
                                }
                                break;
                            case BluetoothConstant.XUEYANG:
                                if (!device.getName().equals("NOVABT_LE") && !device.getName().equals("POD")
                                        && !device.getName().contains(BluetoothConstant.XUEYANG_LIKANG_KRK_PC)) {
                                    return;
                                }
                                break;
                            case BluetoothConstant.XUEYA:
                                if (!BluetoothConstant.XUEYA_JMR.equals(device.getName())
                                        && !BluetoothConstant.XUEYA_JMR2.equals(device.getName())
                                        && !BluetoothConstant.XUEYA_YE680A_YUYUE.equals(device.getName())&&!BluetoothConstant.XUEYA_YE680A_YUYUE2.equals(device.getName())) {
                                    return;
                                }
                                break;
                            case BluetoothConstant.XUETANG:
                                if (!BluetoothConstant.XUETANG_AMX_SANNUO.equals(device.getName())
                                        && !BluetoothConstant.XUETANG_WL_1_SANNUO.equals(device.getName())
                                        && !BluetoothConstant.XUETANG_YUYUE760_YUYUE.equals(device.getName())) {
                                    return;
                                }
                                break;
                            case BluetoothConstant.NIAOCHANGGUI:
                                if (!BluetoothConstant.NIAOJI_HT111A_HANTANG.equals(device.getName())) {
                                    return;
                                }
                                break;
                            case BluetoothConstant.TRIPLE:
                                String currentName = "";
                                if(device.getName().length() > 9){
                                    String subName = device.getName().substring(0, 9);
                                    Log.e("TAG","  获取前九位："+subName);
                                    if(subName.equals("BeneCheck")){
                                        currentName = device.getName();
                                    }
                                }
                                if (currentName.equals("")) {
                                   if(!BluetoothConstant.XUETANG_WL_1_SANNUO.equals(device.getName())){
                                       return;
                                   }
                                }
                                break;
                            default:
                                return;
                        }
                        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                                "macAddress = " + "'" + device.getAddress() + "'");
                        if (btDevices.size() > 0) {
                            // if (btDevices.get(0).isVersion4()) {
                            mDeviceName = device.getName();
                            NovaLog.e(TAG, device.getName());
                            BaseSharedPreferencesUtil.saveStr(mContext, "nova_debug", "deviceName", device.getName());

                            bindDeviceData(device);
                            // }
                        }
                    } else {
                        return;
                    }


                }
            });
        }

    };
    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection2 = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            mBuletoothLeService2 = ((BluetoothLeService.LocalBinder) service).getService();
            NovaLog.e(TAG, "mServiceConnection2 Unable to initialize BluetoothXXX");
            if (!mBuletoothLeService2.initialize()) {
                NovaLog.e(TAG, "mServiceConnection2 Unable to initialize Bluetooth");
                // btn_start.setClickable(false);
                // tv_bleStatus.setText("手机不支持蓝牙");
            }
            // Automatically connects to the device upon successful start-up
            // initialization.
            if(!TextUtils.isEmpty(mDeviceAddress)){
                Log.e("md2service2--",mDeviceAddress+"");
                mBuletoothLeService2.connect(mDeviceAddress);
                isBound = true;
            }
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            mBuletoothLeService2 = null;
            isBound = false;
        }
    };
    CardioChekService mCardioService;
    // Code to manage Service lifecycle.
    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName componentName, IBinder service) {
            if(BluetoothConstant.XUEZHI.equals(queryIndex)){
                mCardioService = ((CardioChekService.LocalBinder)service).getService();
                if(!mCardioService.initialize()){
                    NovaLog.e(TAG, "mServiceConnection Unable to initialize Bluetooth");
                }
                mCardioService.connect(mDeviceAddress);
            }else{
                mBluetoothLeService = ((TJBluetoothLeService.LocalBinder) service).getService();
                NovaLog.e(TAG, "mServiceConnection Unable to initialize BluetoothXXX");
                if (!mBluetoothLeService.initialize()) {
                    NovaLog.e(TAG, "mServiceConnection Unable to initialize Bluetooth");
                }
                mBluetoothLeService.connect(mDeviceAddress);
            }
            isBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if(BluetoothConstant.XUEZHI.equals(queryIndex)){
                mCardioService = null;
            }else{
                mBluetoothLeService = null;
            }
            isBound = false;
        }
    };

    private static IntentFilter makeGattUpdateIntentFilter() {
        final IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_CONNECTED);
        intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(TJBluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(TJBluetoothLeService.ACTION_DATA_AVAILABLE);
        return intentFilter;
    }

    private BroadcastReceiver mGattUpdateReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
//            if(statTZ==-1){
//                return;
//            }
            if(BluetoothConstant.TIZHONGQing.equals(queryIndex) || BluetoothConstant.TIZHONGQing2.equals(queryIndex)){
                if (BLEConstant.ACTION_GATT_CONNECTED.equals(action)) { //蓝牙连接了
//                mConnected = true;
                    Log.e(TAG, "BLE is connected");
                    updateConnectionState("已连接GATT");
                    //invalidateOptionsMenu();
                } else if (BLEConstant.ACTION_GATT_DISCONNECTED.equals(action)) {//蓝牙断开连接
//                mConnected = false;、
                    Log.e(TAG, "ble is disconnect");
//                    updateConnectionState("已连接GATT");
                } else if (BLEConstant.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {//发现蓝牙服务
//                // Show all the supported services and characteristics on the user interface.
                    Log.e(TAG, "discover Service>>>>>>" + mDeviceName);
                    Log.e("mDeviceAddress--",mDeviceAddress+"gatt1---");

                    if (null != mBuletoothLeService2) {
                        if (null != mDeviceName) {
                            //判断是否为 Health Scale
//                            if (mDeviceName.equals(BluetoolUtil.HEALTH_SCALE)) {
//                                //mDeviceName.toLowerCase().startsWith("heal")||mDeviceName.toLowerCase().startsWith("smart")
//                                // 监听 阿里秤 读通道
//                                BleHelper.getInstance().listenAliScale(mBuletoothLeService2);
//                                // 获取用户组 体重以KG为单位
//                                String sendData = BleHelper.getInstance().assemblyAliData(Units.UNIT_KG.getCode(), "01");
//                                // 发送数据
//                                BleHelper.getInstance().sendDateToScale(mBuletoothLeService2, sendData);
//                            } else {
//                                BleHelper.getInstance().sendDateToScale(mBuletoothLeService2, BleHelper.getUserInfo(1, 0, 0, 158, 18, BluetoolUtil.UNIT_KG));
//                            }
                        }
                    }
                } else if (BLEConstant.ACTION_DATA_AVAILABLE.equals(action)) { //接收到数据

                    String readMessage = intent.getStringExtra(BLEConstant.EXTRA_DATA);
                    Log.e(TAG, "Received data : " + readMessage);
                    if (readMessage != null && readMessage.length() == 40) {
                        readMessage = readMessage.substring(0, 22);
                        Log.e(TAG, "=====sub后的：" + readMessage);
                    }
                    Log.e(TAG, "Received the processed data: " + readMessage);
                    if (!TextUtils.isEmpty(readMessage) && readMessage.length() > 10) {
                        Message msg1 = nofityHandler.obtainMessage(BluetoolUtil.RECEIVE_DATA);
                        msg1.obj = readMessage;
                        nofityHandler.sendMessage(msg1);
                    }
                    cancelProgressDialog();
                }
            }else if(BluetoothConstant.XUEZHI.equals(queryIndex)){
                if (CardioChekService.ACTION_GATT_CONNECTED.equals(action)) {
                    updateConnectionState("已连接GATT");
                } else if (CardioChekService.ACTION_GATT_DISCONNECTED.equals(action)) {
                    updateRestartState("断开GATT连接");
                } else if (CardioChekService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                    updateConnectionState("发现蓝牙服务");
                } else if (CardioChekService.ACTION_DATA_AVAILABLE.equals(action)) {
                    // TODO 完成对数据的显示
                    CDKinfo data = (CDKinfo) intent.getSerializableExtra(CardioChekService.EXTRA_DATA);
                    Message msg = new Message();
                    msg.what = 0;
                    msg.obj = data;
                    handler2.sendMessage(msg);
                }
            }else{
                if (TJBluetoothLeService.ACTION_GATT_CONNECTED.equals(action)) {
//                 mConnected = true;
                    updateConnectionState("已连接GATT");
                    // invalidateOptionsMenu();
                } else if (TJBluetoothLeService.ACTION_GATT_DISCONNECTED.equals(action)) {
                    // mConnected = false;
                    updateRestartState("断开GATT连接");
                } else if (TJBluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED.equals(action)) {
                    if(null != mBluetoothLeService){

                    }
                    updateConnectionState("正在通信");
                } else if (TJBluetoothLeService.ACTION_DATA_AVAILABLE.equals(action)) {
                    String data = intent.getStringExtra(TJBluetoothLeService.EXTRA_DATA);
                    // TODO 完成对数据的显示
                    showData(data);
                    cancelProgressDialog();
                }
            }
        }

    };

    private void updateConnectionState(final String resourceId) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {

                String novaName = BluetoothConstant.getNovaDevice(mDeviceName);
                Log.e("novaName---",novaName+"kkk");
                if (TextUtils.isEmpty(novaName)) {
                    showProgressDialog("等待接收数据");
                } else {

                    Log.e(TAG, novaName);
                    String text = "等待接收" + novaName + "数据";
                    try {
                        SpannableStringBuilder builder = GlobalContsBlueThooth.setDifferentText(text, 4,
                                4 + novaName.length());
                        if (builder != null) {
                            showProgressDialogBuilder(builder);
                        } else {
                            showProgressDialog(text);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }
        });
    }

    private void updateRestartState(final String resourceId) {//unregisterReceiver
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {

                    // tv_bleStatus.setText(resourceId);
                    unbindService(mServiceConnection);
                    if(BluetoothConstant.XUEZHI.equals(queryIndex)){
                        mCardioService = null;
                    }else{
                        mBluetoothLeService = null;
                    }
                    cancelProgressDialog();

                    if (!isReceive) {
                        // BaseToast.showShortToast(mContext, "连接中断");
                        String novaName = BluetoothConstant.getNovaDevice(mDeviceName);
                        if (TextUtils.isEmpty(novaName)) {
                            showTextDialog("连接中断");
                            tv_state.setText("连接中断");
                        } else {
                            showTextDialog("连接" + novaName + "中断");
                            tv_state.setText("连接" + novaName + "中断");
                        }
                        lay_celiang.setVisibility(View.VISIBLE);
                        if (mGattUpdateReceiver != null) {
                            mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
                            bapp = false;
                            isRegisterReceiver=false;
                            mGattUpdateReceiver = null;
                        }

                        mBluetoothLeService = null;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        });
    }

    private void showData(final String data) {

        isReceive = true;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                System.out.println(queryIndex + "*********************");
                Log.e("showData()", data + "*********************");

                cancelProgressDialog();
                if (BluetoothConstant.XUEYA_JMR.equals(mDeviceName)
                        || BluetoothConstant.XUEYA_JMR2.equals(mDeviceName)) {

                    if ("测量失败，请重新测量！".equals(data)) {
                        lay_result.setVisibility(View.VISIBLE);
                        tv_state.setText("测量失败，请重新测量！");
                        tv_result.setText("");
                    } else if ("臂式血压计电量不足，请及时充电".equals(data)) {

                        lay_result.setVisibility(View.VISIBLE);
                        tv_state.setText("电量不足，无法完成测量！");
                        tv_result.setText("");
                    }
                    else {
                        lay_result.setVisibility(View.VISIBLE);
                        String result = DeviceShowSaveData.getDataShow(data, mDeviceName);
                        Log.e("showData()3333", result + "*********************");
                        tv_result.setText("测量结果：\n        " + result);
                        tv_state.setText("获取测量结果成功");
                    }
                    lay_celiang.setVisibility(View.VISIBLE);
                } else if(mDeviceName.equals(BluetoolUtil.HEALTH_SCALE)){
                    //体重
                    lay_result.setVisibility(View.VISIBLE);
                    lay_celiang.setVisibility(View.VISIBLE);
                    //保存体重
                    String result = DeviceShowSaveData.getDataShow(data, mDeviceName);
                    tv_result.setText("测量结果：\n        " + result);
                    tv_state.setText("获取测量结果成功");
                    if (mGattUpdateReceiver != null) {
//                        mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
//                        bapp = false;
//                        mGattUpdateReceiver = null;
                        if (scanHandler != null) {
                            scanHandler.removeCallbacks(scanThread);
                        }
//                        unbindService(mServiceConnection2);
//                        mBuletoothLeService2= null;
                        isFind = false;
                        statTZ = -1;
                    }
//                    mBluetoothLeService = null;
                }else if(BluetoothConstant.XUEZHI_CARDIOCHEK.equals(mDeviceName)){
                    lay_result.setVisibility(View.VISIBLE);
                    lay_celiang.setVisibility(View.VISIBLE);
                    //保存体重
                    String result = DeviceShowSaveData.getDataShow(data, mDeviceName);
                    tv_result.setText("测量结果：\n        " + result);
                    tv_state.setText("获取测量结果成功");
                    cancelProgressDialog();
                    Log.e("showData()xuezhi", result + "********");
                } else {
                    lay_result.setVisibility(View.VISIBLE);
                    lay_celiang.setVisibility(View.VISIBLE);
                    // if(TextUtils.isEmpty(mDeviceName)&&isBlooth2){
                    // mDeviceName="NOVAEW";
                    // }
                    String result = DeviceShowSaveData.getDataShow(data, mDeviceName);
                    tv_result.setText("测量结果：\n        " + result);
                    tv_state.setText("获取测量结果成功");
                    cancelProgressDialog();
                    // TODO
                    if (BluetoothConstant.TIWEN.equals(queryIndex)) {
                        if (isBlooth2) {
                            // 蓝牙2.0
                            if (isServiceRunning(getApplicationContext(),
                                    "com.novabluetooth.services.bluetooth2.ListenService")) {
                                stopService(new Intent(SBCLActivity.this, ListenService.class));
                            }

                        } else {
                            if (mGattUpdateReceiver != null) {
//                                mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
                                bapp = false;
//                                isRegisterReceiver=false;
                                mGattUpdateReceiver = null;
                            }

                            mBluetoothLeService = null;
                        }
                    } else {
                        if (mGattUpdateReceiver != null) {

//                            mContext.getApplicationContext().unregisterReceiver(mGattUpdateReceiver);
//                            isRegisterReceiver=false;
                            bapp = false;
                           mGattUpdateReceiver = null;
                        }

                        mBluetoothLeService = null;
                    }

                }

            }
        });
    }

    /**
     * 绑定开始连接设备
     */
    public void bindDeviceData(BluetoothDevice device) {
        if (mScanning) {
            mScanning = false;
            scanLeDevice(false);
        }

        editor.putString("deviceName", device.getName());
        editor.commit();

        mDeviceAddress = device.getAddress();
        System.out.println(device.getName() + "********************");
        Intent gattServiceIntent = null;
        switch (queryIndex) {
            case BluetoothConstant.XUEZHI:
                if(BluetoothConstant.XUEZHI_CARDIOCHEK.equals(device.getName())){
                    gattServiceIntent = new Intent(mContext, CardioChekService.class);
                }
                break;
            case BluetoothConstant.TIWEN:
                if (BluetoothConstant.TIWEN_EWQ_HTD.equals(device.getName())
                        || BluetoothConstant.TIWEN_EWENQ_HTD.equals(device.getName())
                            || BluetoothConstant.TIWEN_EWENQ_HTD3.equals(device.getName())) {
                    // Intent gattServiceIntent = new Intent(mContext,
                    // TJBluetoothLeService.class);
                    gattServiceIntent = new Intent(mContext, TiWenHtdService.class);
                } else if (BluetoothConstant.TIWEN_EWQ_NOVA.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, TiWenNovaService.class);
                }else if (BluetoothConstant.TW_JK.equals(device.getName())){
                    gattServiceIntent = new Intent(mContext, TiWenJKService.class);
                }
                break;
            case BluetoothConstant.XUETANG:
                if (BluetoothConstant.XUETANG_AMX_SANNUO.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, XueTangAWXSanNuoService.class);
                } else if (BluetoothConstant.XUETANG_WL_1_SANNUO.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, XueTangWL1SanNuoService.class);
                }
                break;
            case BluetoothConstant.TIZHONG:
                if (BluetoothConstant.TIZHONG_NOVA.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, TiZhongNovaService.class);
                } else if ( BluetoothConstant.TIZHONG_FATSCALE.equals(device.getName())){
                    gattServiceIntent = new Intent(mContext, TiZhongFatScaleService.class);//TIZHONG_HEALTH
                }
                    break;
            case BluetoothConstant.TIZHONGQing:
                String currentName = "";
                if(device.getName().length() > 5){
                    String subName = device.getName().substring(0, 5);
                    Log.e("TAG","获取前九位："+subName);
                    if(subName.contains("Body")){
                        currentName = device.getName();
                        gattServiceIntent = new Intent(mContext, TiZhongFatScaleService.class);

                    }
                }
                break;
            case BluetoothConstant.TIZHONGQing2:
                if ( BluetoothConstant.TIZHONG_HEALTH.equals(device.getName())){
                    gattServiceIntent = new Intent(mContext, TiZhongFatScaleService.class);
                }
                break;
            case BluetoothConstant.XUEYANG:
                if (BluetoothConstant.XUEYANG_LIKANG_KRK.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, XueYangKRKService.class);
                } else if (device.getName().contains(BluetoothConstant.XUEYANG_LIKANG_KRK_PC)) {
                    Log.e("xiaoxin","hhhhhhhhhhh");
                    initXueYangBle();
                }else if (BluetoothConstant.XUEYANG_NOVA.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, XueYangNovaService.class);
                }
                break;
            case BluetoothConstant.XUEYA:
                if (BluetoothConstant.XUEYA_JMR.equals(device.getName())
                        || BluetoothConstant.XUEYA_JMR2.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, XueYaB61TJMRService.class);
                } else if (BluetoothConstant.XUEYA_YE680A_YUYUE.equals(device.getName())||BluetoothConstant.XUEYA_YE680A_YUYUE2.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, XueYaYuYue760Service.class);
                }
                break;
            case BluetoothConstant.NIAOCHANGGUI:
                if (BluetoothConstant.NIAOJI_HT111A_HANTANG.equals(device.getName())) {
                    gattServiceIntent = new Intent(mContext, NiaoJiht111AHanTangService.class);
                }
                break;
            case BluetoothConstant.TRIPLE:
                    gattServiceIntent = new Intent(mContext, TripleService.class);
                break;
            default:
                break;
        }
        if (gattServiceIntent != null) {
            mContext.bindService(gattServiceIntent, mServiceConnection, mContext.BIND_AUTO_CREATE);
        }
    }
    /**
     * 关闭并退出
     *
     * @author 王婷婷
     * @date 2017年3月18日 下午5:13:21
     */
    public void closeAndExit() {
        System.out.print("NoticeService关闭");
        scanLeDevice(false);
        try {


            if (isRegisterReceiver) {
                if (mGattUpdateReceiver != null) {
                    isRegisterReceiver = false;
                    mContext.unregisterReceiver(mGattUpdateReceiver);
                }
            }
            if(mGattUpdateReceiver!=null){
                unregisterReceiver(mGattUpdateReceiver);
            }
            if (isBound) {
                isBound = false;
                if (mServiceConnection != null) {
                    mContext.unbindService(mServiceConnection);
                }
            }
            if (mBluetoothLeService != null) {
                mBluetoothLeService.close();
                mBluetoothLeService = null;
            }
            if(mCardioService != null){
                mCardioService.close();
                mCardioService = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 蓝牙4.0
//        closeAndExit();
        bluetoothManager.stopBTAffair();
        if (msgReceiver != null) {
            unregisterReceiver(msgReceiver);
        }
        if(mBuletoothLeService2!=null){
            scanHandler.removeCallbacks(scanThread);
            unbindService(mServiceConnection2);
            mBuletoothLeService2 = null;
        }
        try{
            if(isRegisterReceiver){
                mContext.unregisterReceiver(mGattUpdateReceiver);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
        if(mCardioService != null){
            mCardioService = null;
        }

        if(isbind){
            mBuletoothLeService2 = null;
            isbind = false;
        }
        // 蓝牙2.0
        if (isServiceRunning(getApplicationContext(), "com.novabluetooth.services.bluetooth2.ListenService")) {
            stopService(new Intent(SBCLActivity.this, ListenService.class));
        }
        stopBle();
    }


    /**
     * 心电图图片
     *
     * @author 王婷婷
     * @date 2017年7月18日 下午5:08:58
     */
    private void initEcgJpg(Intent intent) {
        // intent.getStringExtra("tj_result")
        if (intent.hasExtra("JPG_URL")) {
            String url = intent.getStringExtra("JPG_URL");
            Log.w("ttt", url);
            // String
            // url="/storage/emulated/0/ECGDATA/JPEG/-20160315132210.jpeg";
            if (!TextUtils.isEmpty(url)) {
                Bitmap bitmap = getLocalBitmap(url);
                show_img.setImageBitmap(bitmap);
                show_img.setVisibility(View.VISIBLE);
                queryIndex = BluetoothConstant.ECG;
                bt_cklsjl.setText("查看心电历史记录");
            } else {
                show_img.setVisibility(View.GONE);
            }
        }

    }

    public Bitmap getLocalBitmap(String url) {

        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }
    boolean bapp = false;
    @Override
    protected void onResume() {
        super.onResume();
        isBlooth2 = SPUtil.getisBlooth2(SBCLActivity.this, false);
//        mContext.getApplicationContext().registerReceiver(mGattUpdateReceiver, BluetoothUtils.makeGattUpdateIntentFilter());
//        bapp = true;
//        if (mBluetoothLeService != null) {
//            final boolean result = mBluetoothLeService.connect(mDeviceAddress);
//            Log.e(TAG, "onResume_admin1=" + result);
//        }
////        if(mCardioService != null){
////            final boolean result = mCardioService.connect(mDeviceAddress);
////        }
//        if(mBuletoothLeService2!=null){
//            final boolean result2 = mBuletoothLeService2.connect(mDeviceAddress);
//            Log.e(TAG, "onResume_admin2=" + result2);
//        }
    }
    /**
     * 初始化蓝牙2.0
     *
     * @author 王婷婷
     * @date 2017年8月1日 下午3:47:36
     */
    private void initBluetooth2() {
        // 2.0与4.0蓝牙同时开启，第一阶段做2.0尿机
        getBoolthQuanXian();
        // 蓝牙2.0 的尿机
        BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (mBluetoothAdapter == null) {
            showTextDialog("本机没有找到蓝牙硬件或驱动！");
        } else {
            if (!mBluetoothAdapter.isEnabled()) {
                showTextDialog("蓝牙没有打开！");
            } else {

                // //启动修改蓝牙可见性的Intent
                // Intent intent = new
                // Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
                // //设置蓝牙可见性的时间，方法本身规定最多可见300秒
                // intent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
                // 300);
                // startActivity(intent);

                if (!isServiceRunning(getApplicationContext(), "com.novabluetooth.services.bluetooth2.ListenService")) {
                    Log.w(TAG, "initBluetooth2 开始测量，ListenService没有运行，开启服务");
                    showProgressDialog("正在搜索设备");
                    startService(new Intent(SBCLActivity.this, ListenService.class));
                }

            }
        }
    }

    public void getBoolthQuanXian() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_ACCESS_COARSE_LOCATION);
            // 判断是否需要 向用户解释，为什么要申请该权限
            if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_CONTACTS)) {
                Toast.makeText(this, "shouldShowRequestPermissionRationale", Toast.LENGTH_SHORT).show();
            }
        }
    }

    // 蓝牙服务判断
    public static boolean isServiceRunning(Context context, String serviceName) {
        boolean isRunning = false;
        android.app.ActivityManager am = (android.app.ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
        List<android.app.ActivityManager.RunningServiceInfo> infos = am.getRunningServices(500);
        for (android.app.ActivityManager.RunningServiceInfo info : infos) {
            if (info.service.getClassName().equals(serviceName)) {
                Log.e(TAG, "initBluetooth2服务已经运行");
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }
    /**
     * PopWindow 实体bean
     */
    List<PopDataBean> datasOptions = new ArrayList<>();
    private PopWindow popWindowOptions = null;
    //选中单条
    private int mnSeclectItem = -1;
    //单条id
    private String mnSeclectItemID = "";

    /**
     * 初始化Popwindow
     */
    private void initPopDatas() {
        if(datasOptions == null){
            datasOptions = new ArrayList<>();
        }

        datasOptions.clear();

        datasOptions.add(new PopDataBean("0", "华清心电"));
        datasOptions.add(new PopDataBean("1", "力康快速心电监测仪"));

        // 实例化PopWindow
        popWindowOptions = new PopWindow(this);
        // 设置点击其他位置mTestPopwindow2消失
        popWindowOptions.setOnDismissListener(this);
    }

    @Override
    public void onDismiss() {

    }

    /**
     * 设置popwindow点击事件
     */
    private void onPopwindowOptions() {
        if (popWindowOptions == null) {
            return;
        }

        //回到接受
        popWindowOptions.setOnData(new PopWindow.OnGetData() {

            //记录上一次选中的item
            @Override
            public int onSeclectItem() {
                return mnSeclectItem;
            }

            @Override
            public void onDataCallBack(int nSectlect, ArrayList<PopDataBean> mArrayList) {
                mnSeclectItem = nSectlect;
                String name = mArrayList.get(nSectlect).getName();
//                btn_connect.setText(name);

                mnSeclectItemID = mArrayList.get(nSectlect).getIndex();
                //设置操作事件
                clickPopData(mnSeclectItemID);
            }


            //传递数据源过去
            @Override
            public ArrayList<PopDataBean> onArrayList() {
                return (ArrayList<PopDataBean>) datasOptions;
            }
        });
        popWindowOptions.showAtLocation(gd_view, Gravity.CENTER, 10, 10);
    }
    /**
     * 设置操作事件
     */
    private void clickPopData(String index) {
        Intent intent =null;

        if("0".equals(index)){
            //华清心电
            intent = new Intent(SBCLActivity.this, HQXDActivity.class);
        }else if("1".equals(index)){
            //力康快速检测心电
            intent = new Intent(SBCLActivity.this, MainPC80B.class);
        }
        if (intent != null ){
            startActivity(intent);
        }

    }

    private com.novabluetooth.views.iknetbluetoothlibrary.BluetoothManager.OnBTMeasureListener onBTMeasureListener = new com.novabluetooth.views.iknetbluetoothlibrary.BluetoothManager.OnBTMeasureListener() {
        @Override
        public void onRunning(String running) {
            //测量过程中的压力值
            Log.e(TAG,"实时数据："+running);
        }

        @Override
        public void onPower(String power) {
            //测量前获取的电量值
        }

        @Override
        public void onMeasureResult(MeasurementResult result) {
            //测量结果
            cancelProgressDialog();
            try{
                lay_result.setVisibility(View.VISIBLE);
                String results = DeviceShowSaveData.getDataShow(result.getCheckShrink()+";"+result.getCheckDiastole()+";"+result.getCheckHeartRate()+";", BluetoothConstant.XUEYA_YE680A_YUYUE);
                Log.e("showData()3333", results + "*********************");
                tv_result.setText("测量结果：\n        " + results);
                tv_state.setText("获取测量结果成功");
                cancelProgressDialog();
                Log.e(TAG,"测量结果："+result.getCheckShrink()+";"+result.getCheckDiastole()+";"+result.getCheckHeartRate()+";");
            }catch (Exception e){
                System.out.println("报异常了："+e.toString());
            }
//            startActivity(intent);
//            finish();
        }

        @Override
        public void onMeasureError() {
            //测量错误
            Toast.makeText(SBCLActivity.this,
                    "测量失败", Toast.LENGTH_SHORT).show();
            cancelProgressDialog();
        }

        @Override
        public void onFoundFinish(List<BluetoothDevice> deviceList) {
            //搜索结束，deviceList.size()如果为0，则没有搜索到设备
//            if(deviceList.size() == 0){
//                cancelProgressDialog();
//                Toast.makeText(SBCLActivity.this, "未搜索到设备", Toast.LENGTH_SHORT).show();
//            }
        }

        @Override
        public void onDisconnected(BluetoothDevice device) {
            //断开连接
            Toast.makeText(SBCLActivity.this, "断开连接", Toast.LENGTH_SHORT).show();

            cancelProgressDialog();
        }

        @Override
        public void onConnected(boolean isConnected, BluetoothDevice device) {
            //是否连接成功
            if(isConnected){
                showProgressDialog("等待接收脉搏波血压计数据");
            }else{
                try {
                    Toast.makeText(SBCLActivity.this,
                            getResources().getString(R.string.unable_to_connect_device) + device.getName(), Toast.LENGTH_SHORT).show();
                }catch (Exception e){
                    System.out.println("异常："+e.toString());
                }
            }
        }
    };


    private void dealStopMeasureBtn() {
        Log.e("A","走开始了"+bluetoothManager.isConnectBT());

        //蓝牙已经打开，开始搜索、连接和测量
        if(bluetoothManager.isConnectBT()){
            bluetoothManager.startMeasure();
        }else{
            bluetoothManager.startBTAffair(onBTMeasureListener);
        }
        showProgressDialog("正在搜索" + mTypename + "设备");
    }
    private BluetoothAdapter _bluetooth = BluetoothAdapter.getDefaultAdapter();

    private void setBluetooth() {

        if (_bluetooth == null) {
            Toast.makeText(this,"本机没有找到蓝牙硬件或驱动！",Toast.LENGTH_LONG).show();
            finish();
            return;
        }

        if (!_bluetooth.isEnabled()) {
            //提醒用户打开蓝牙
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, 1);
        }else{
            //蓝牙已经打开，开始搜索、连接和测量
            bluetoothManager.startBTAffair(onBTMeasureListener);
        }

    }

    private BleDevice connBleDevice;
    private String uuid_service = "6e400001-b5a3-f393-e0a9-e50e24dcca9e";//服务uuid
    private String uuid_characteristic_write = "6e400002-b5a3-f393-e0a9-e50e24dcca9e";//写
    private String uuid_characteristic_notify = "6e400003-b5a3-f393-e0a9-e50e24dcca9e";//读
    private boolean isScan = false;//是否正在扫描
    private String mBloodOxygen;//血氧值
    private String mHeartRate;//心率值
    private boolean isConect = false;//是否连接ble

    private void initXueYangBle() {
        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                "name = '" + BluetoothConstant.XUEYANG_LIKANG_KRK_PC_NAME + "'");
        String macAddress = "";
        if (btDevices != null && btDevices.size() > 0) {
            macAddress = btDevices.get(0).getMacAddress();
        }
        if (TextUtils.isEmpty(macAddress)) {
            ToastUtils.showShort("请先绑定血氧设备");
        }
        boolean enable = mBluetoothAdapter.enable();
        com.blankj.utilcode.util.LogUtils.e("mBluetoothAdapter.enable()" + enable);
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(macAddress)                  // 只扫描指定mac的设备，可选
//                .setDeviceName(true,"PC-60F")
//                .setAutoConnect(true)      // 连接时的autoConnect参数，可选，默认false
//                .setDeviceName(true, "Chipsea-BLE")         // 只扫描指定广播名的设备，可选
                .setScanTimeOut(15000)              // 扫描超时时间，可选，默认10秒；小于等于0表示不限制扫描时间
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);

        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                Log.e(TAG,"*********开始结束**************");
            }

            @Override
            public void onScanStarted(boolean success) {
                Log.e(TAG,"*********开始扫描**************" + success );
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                Log.e(TAG,"*********onScanning**************");
                connectionXueYangBle(bleDevice);
            }
        });
    }

    private void connectionXueYangBle(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                Log.e(TAG,"*********开始连接**************");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG,"*********连接失败**************");
            }

            @Override
            public void onConnectSuccess(BleDevice bledevic, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接成功**************");
                showProgressDialog("等待接收数据");
                // 连接成功，BleDevice即为所连接的BLE设备（主线程）
//                blueToothState.setText("蓝牙已连接");
                setStatusStop();
                isScan = false;
                connBleDevice = bledevic;
                //可以延迟500ms左右打开通知和发送通知
                //定时主动发送心跳包
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
//                        if(isConect){
                        if(true){
                            bleWrite(XueYangHexUtils.hexStringToBytes("80"), bleDevice, uuid_service, uuid_characteristic_write);
                            bleNotify(bleDevice, uuid_service, uuid_characteristic_notify);
                        }
                    }
                },200);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接中断**************");
                isScan = false;

                setStatusPre();
                BleManager.getInstance().stopNotify(bleDevice, uuid_service, uuid_characteristic_notify);
                BleManager.getInstance().disconnect(bleDevice);
            }
        });
    }

    /**
     * 向蓝牙发送写入数据
     * @param data 写入的byte数据
     */
    @SuppressLint("CheckResult")
    private void bleWrite(final byte[] data, final BleDevice bleDevice, final String uuid_service,
                          String uuid_characteristic_write) {
        BleManager.getInstance().write(
                bleDevice,
                uuid_service,
                uuid_characteristic_write,
                data,
                new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        // 发送数据到设备成功
                        Log.e(TAG, "写入数据成功:" + Arrays.toString(data) );
                    }
                    @Override
                    public void onWriteFailure(BleException exception) {
                        // 发送数据到设备失败
                        Log.e(TAG, "写入数据失败:" + Arrays.toString(data) );
                    }
                });
    }

    /**
     * 订阅接受广播通知
     */
    private void bleNotify(BleDevice bleDevice, String uuid_service, String uuid_characteristic_notify) {
        BleManager.getInstance().notify(
                bleDevice,
                uuid_service,
                uuid_characteristic_notify,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        // 打开通知操作成功
                    }
                    @Override
                    public void onNotifyFailure(BleException exception) {
                        // 打开通知操作失败
                    }
                    @Override
                    public void onCharacteristicChanged(final byte[] data) {
                        // 打开通知后，设备发过来的数据将在这里出现
                        Log.e(TAG, "onCharacteristicChanged: " + "收到data==" + Arrays.toString(data)  );

//                        if(connetstatus_tv != null){
//                            connetstatus_tv.setText("心率血氧仪已连接");
//                        }
                        try {
                            cancelProgressDialog();
                            cancelTextDialog();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        analysisData(XueYangHexUtils.formatHexString(data, true));
                    }
                });
    }

    //中间数据
    private List<String> tempArrays = new ArrayList<>();

    /**
     * 解析数据
     * @param formatHexString
     */
    private void analysisData(String formatHexString) {
        String[] strings = formatHexString.split(" ");
        tempArrays.clear();
        if(strings.length < 8){
            return;
        }else if(strings.length > 12){
            for(int i = 0; i< 12 ; i++){
                tempArrays.add(strings[i]);
            }
        }else{
            tempArrays.addAll(Arrays.asList(strings));
        }

        if(BleHeartOxygenConversion.isHeartRateTrue(tempArrays) && BleHeartOxygenConversion.isDataTrue(tempArrays)){
            //检测数据长度是否符合 不符合略过
            mBloodOxygen = Integer.parseInt(tempArrays.get(5), 16)+"";//血氧浓度
            mHeartRate = Integer.parseInt(tempArrays.get(7)+tempArrays.get(6), 16)+"";//脉搏（心率）

            lay_result.setVisibility(View.VISIBLE);
            tv_state.setText("获取测量结果成功");
            tv_result.setText("脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
            Log.e("showData()3333", "脉率:" + mHeartRate + "bpm\t\t"+"血氧:" + mBloodOxygen + "%");
        }

    }

    private void setStatusPre() {
//        if (connetstatus_tv == null || descripte_tv == null) {
//            return;
//        }
        isConect = false;
//        connetstatus_tv.setText("心率血氧仪未连接");
//        descripte_tv.setText("点击左侧按钮，连接设备!");
        DeviceShowSaveData.getDataShow( mBloodOxygen + "/" + mHeartRate, BluetoothConstant.XUEYANG_LIKANG_KRK);
    }

    private void setStatusStop() {
//        if (connetstatus_tv == null || descripte_tv == null) {
//            return;
//        }
        isConect = true;
//        connetstatus_tv.setText("心率血氧仪已连接");
//        descripte_tv.setText("请使用设备开始测量心率血氧!");
    }

    private void stopBle() {
        //调用该方法后，如果当前还处在扫描状态，会立即结束，并回调`onScanFinished`方法。
        if (isScan) {
            BleManager.getInstance().cancelScan();
        }
        if (connBleDevice != null) {
            BleManager.getInstance().stopNotify(connBleDevice, uuid_service, uuid_characteristic_notify);
            //断开设备
            BleManager.getInstance().disconnect(connBleDevice);
        }

    }

    private void sacnTwjBle() {
        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                "name = '" + TwjConstans.DEVICE_NAME_TYPENAME + "'");
        String macAddress = "";
        if (btDevices != null && btDevices.size() > 0) {
            macAddress = btDevices.get(0).getMacAddress();
        }
        if (TextUtils.isEmpty(macAddress)) {
            ToastUtils.showShort("请先绑定爱奥乐体温计设备");
            return;
        }
        blueToothState.setText("蓝牙已打开");
        showProgressDialog("正在搜索体温计设备");
        Log.e(TAG, "sacnTwjBle: "+macAddress );
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
//                .setDeviceName(true,TwjConstans.DEVICE_NAME)
                .setDeviceMac(macAddress)
                .setAutoConnect(true)
                .setScanTimeOut(15000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
                Log.e(TAG,"*********开始结束**************");
            }

            @Override
            public void onScanStarted(boolean success) {
                Log.e(TAG,"*********开始扫描**************");
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                Log.e(TAG,"*********onScanning**************");
                connectionTwjBle(bleDevice);
            }
        });
    }

    private void connectionTwjBle(final BleDevice bleDevice) {
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                Log.e(TAG,"*********开始连接**************");
            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG,"*********连接失败**************" + exception.toString());
            }

            @Override
            public void onConnectSuccess(BleDevice bledevic, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接成功**************");
                blueToothState.setText("蓝牙已连接");
                cancelTextDialog();
                cancelProgressDialog();
                // 连接成功，BleDevice即为所连接的BLE设备（主线程）
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //发送00信息
                        byte[] data_00 = ZHexUtil.hexStringToBytes(ZHexUtil.getSendHex(0));
                        bleTwjWrite(data_00,bleDevice,TwjConstans.GATT_SERVICE_PRIMARY,
                                TwjConstans.CHARACTERISTIC_WRITEABLE);
                        bleTwjNotify(bleDevice,TwjConstans.GATT_SERVICE_PRIMARY,
                                TwjConstans.CHARACTERISTIC_READABLE);
                    }
                },200);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                Log.e(TAG,"*********连接中断**************");
                blueToothState.setText("蓝牙已断开");
            }
        });

    }

    private void bleTwjWrite(final byte[] data, final BleDevice bleDevice, final String uuid_service,
                             String uuid_characteristic_write) {
        BleManager.getInstance().write(
                bleDevice,
                uuid_service,
                uuid_characteristic_write,
                data,
                new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        // 发送数据到设备成功
                        Log.e(TAG, "写入数据成功:" + Arrays.toString(data) );
                    }
                    @Override
                    public void onWriteFailure(BleException exception) {
                        // 发送数据到设备失败
                        Log.e(TAG, "写入数据失败:" + Arrays.toString(data) );
                    }
                });
    }

    /**
     * 订阅接受广播通知
     */
    private void bleTwjNotify(BleDevice bleDevice, String uuid_service, String uuid_characteristic_notify) {
        BleManager.getInstance().notify(
                bleDevice,
                uuid_service,
                uuid_characteristic_notify,
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        // 打开通知操作成功
                    }
                    @Override
                    public void onNotifyFailure(BleException exception) {
                        // 打开通知操作失败
                    }
                    @Override
                    public void onCharacteristicChanged(final byte[] data) {
                        // 打开通知后，设备发过来的数据将在这里出现
                        Log.e(TAG, "onCharacteristicChanged: " + "收到data==" + Arrays.toString(data)  );
                        showContent(data);
                    }
                });
    }

    private void showContent(byte[] data) {
        if (null == data) return;
        byte index0 = data[0];
        if (index0 != 85) return;
        byte index2 = data[2];
        if (index2 == 3) {//Device upload results
            byte index3 = data[3];//Year
            byte index4 = data[4];//Month
            byte index5 = data[5];//Day
            byte index6 = data[6];//Hour
            byte index7 = data[7];//Minute
            byte[] valueArr = {data[10], data[9]};
            //10+9 Convert to decimal,And then  divide by 100,get the temperature
            String strValue = ZHexUtil.encodeHexStr(valueArr);
            int value = Integer.valueOf(strValue, 16);
            Log.e("zdw", "value --" + value);
            //跟体温计结果显示保持一致：丢弃小数点后第二位
            String valueStr = StringUtil.formatTo1ROUNDDOWN((double) value / 100);
            String str = String.format(" 温度值:%s℃", valueStr);
            lay_result.setVisibility(View.VISIBLE);
            tv_state.setText("获取测量结果成功");
            tv_result.setText(str);
            String results = DeviceShowSaveData.getDataShow(valueStr, TwjConstans.DEVICE_NAME);
            Log.e("showData()3333", results + "*********************");
        } else if (index2 == 5) {

        }
    }

    private void sacnPWBle() {
        List<BTDevice> btDevices = NovaApplication.fdbmanger.findAllBTByWhere(BTDevice.class,
                "name = '" + BluetoothConstant.PW_01DEVICE_NAME_TYPENAME + "'");
        String macAddress = "";
        if (btDevices != null && btDevices.size() > 0) {
            macAddress = btDevices.get(0).getMacAddress();
        }
        if (TextUtils.isEmpty(macAddress)) {
            ToastUtils.showShort("请先绑定血脂设备");
            return;
        }

        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setDeviceMac(macAddress)
                .setScanTimeOut(15000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                connectionPwBle(bleDevice);
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
            }
        });
    }

    private void connectionPwBle(BleDevice bleDevice) {
        showProgressDialog("正在连接");
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {
                blueToothState.setText("蓝牙开始连接");

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                Log.e(TAG, "onConnectFail: " +  exception.toString());
                blueToothState.setText("蓝牙连接失败");
                cancelProgressDialog();
                getPwNotify(bleDevice);
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: " + bleDevice.getMac() );
                blueToothState.setText("蓝牙已连接");
                cancelTextDialog();
                cancelProgressDialog();
                getPwNotify(bleDevice);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开连接");
            }
        });
    }

    private void getPwNotify(final BleDevice bleDevice) {

        BleManager.getInstance().notify(bleDevice,
                UUID_SERVICE_PW.toString(),
                UUID_NOTIFY_PW.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: " );
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " +exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {

                        Log.e(TAG, "onCharacteristicChanged: "+ data );
                        //接收数据
                        String hexString = HexUtil.formatHexString(data);
                        Log.e(TAG, "onCharacteristicChanged: "+ hexString );
                        resultData(data);
                    }
                });
    }

    private void resultData(byte[] data) {
        try {
            if (data.length > 5) {
                StringBuilder stringBuilder = new StringBuilder();
                String hexStr = HexUtil.formatHexString(data);
                String cmd = hexStr.substring(4, 6);
                System.out.println(cmd);
                //06代表测试结果
                if ("05".equals(cmd)) {
                    String data1 = hexStr.substring(8, 10);
                    lay_result.setVisibility(View.VISIBLE);
                    if ("01".equals(data1)) {
                        tv_state.setText("光化学试纸插入");
                        Log.e(TAG, "光化学试纸插入 " );
                    } else if ("02".equals(data1)) {
                        tv_state.setText("光化学试纸拔出");
                        Log.e(TAG, "光化学试纸拔出 " );
                    }else if ("03".equals(data1)) {
                        tv_state.setText("光化学试纸合格");
                        Log.e(TAG, "光化学试纸合格 " );
                    }else if ("04".equals(data1)) {
                        tv_state.setText("光化学试纸过期");
                        Log.e(TAG, "光化学试纸过期 " );
                    }else if ("05".equals(data1)) {
                        tv_state.setText("光化学试纸已滴血");
                        Log.e(TAG, "光化学试纸已滴血" );
                    }
                }else if ("06".equals(cmd)) {
                    PwBean pwBean = new PwBean();
                    Log.e(TAG, "测量完成" );
                    //DATA1：01代表血脂卡
                    String data1 = hexStr.substring(8, 10);
                    System.out.println(data1);
                    if ("01".equals(data1)) {
                        String data2 = hexStr.substring(10, 12);
                        String data3 = hexStr.substring(12, 14);
                        int checkTc = SBCLUtils.checkDataCompliance(data2, data3);
                        if (checkTc == 1) {
                            double tc = (Integer.parseInt(data2, 16)*256 + Integer.parseInt(data3, 16))/100.0;
                            pwBean.setTc(tc);
                            System.out.println("总胆固醇:"+tc + "mmol/L");
                            stringBuilder.append("总胆固醇:"+tc + "mmol/L" + "\n");
                        }else if (checkTc == 2) {
                            stringBuilder.append("总胆固醇:测试结果大于测试范围");
                            System.out.println("测试结果大于测试范围");
                        }else if (checkTc == 3){
                            stringBuilder.append("总胆固醇:测试结果小于测试范围");
                            System.out.println("测试结果小于测试范围");
                        }

                        String data4 = hexStr.substring(14, 16);
                        String data5 = hexStr.substring(16, 18);
                        int checkTg = SBCLUtils.checkDataCompliance(data4, data5);
                        if (checkTg == 1) {
                            double tg = (Integer.parseInt(data4, 16)*256 + Integer.parseInt(data5, 16))/100.0;
                            pwBean.setTg(tg);
                            System.out.println("甘油三酯:"+tg);
                            stringBuilder.append("甘油三酯:"+tg + "mmdl/L\n");
                        }else if (checkTg == 2) {
                            System.out.println("测试结果大于测试范围");
                            stringBuilder.append("甘油三酯:测试结果大于测试范围");
                        }else if (checkTg == 3){
                            System.out.println("测试结果小于测试范围");
                            stringBuilder.append("甘油三酯:测试结果小于测试范围");
                        }

                        String data6 = hexStr.substring(18, 20);
                        String data7 = hexStr.substring(20, 22);
                        int checkHdl = SBCLUtils.checkDataCompliance(data6, data7);
                        if (checkHdl == 1) {
                            double hdl = (Integer.parseInt(data6, 16)*256 + Integer.parseInt(data7, 16))/100.0;
                            pwBean.setHdl(hdl);
                            stringBuilder.append("高密:"+hdl + "mmdl/L\n");
                        }else if (checkHdl == 2) {
                            System.out.println("测试结果大于测试范围");
                            stringBuilder.append("高密:测试结果大于测试范围");
                        }else if (checkHdl == 3){
                            System.out.println("测试结果小于测试范围");
                            stringBuilder.append("高密:测试结果小于测试范围");
                        }

                        String data8 = hexStr.substring(22, 24);
                        String data9 = hexStr.substring(24, 26);
                        int checkLdl = SBCLUtils.checkDataCompliance(data8, data9);
                        if (checkLdl == 1) {
                            double ldl = (Integer.parseInt(data8, 16)*256 + Integer.parseInt(data9, 16))/100.0;
                            pwBean.setLdl(ldl);
                            stringBuilder.append("低密:"+ldl + "mmdl/L\n");
                        }else if (checkLdl == 2) {
                            System.out.println("测试结果大于测试范围");
                            stringBuilder.append("低密:测试结果大于测试范围");
                        }else if (checkLdl == 3){
                            System.out.println("测试结果小于测试范围");
                            stringBuilder.append("低密:测试结果小于测试范围");
                        }

                    }

                    lay_result.setVisibility(View.VISIBLE);
                    tv_state.setText("获取测量结果成功");
                    tv_result.setText(stringBuilder.toString());
                    if (pwBean.getTc() > 0) {
                        tv_state.setText("获取测量结果成功");
                        //有效数据在存入数据库
                        String json = GsonUtils.toJson(pwBean);
                        Log.e(TAG, "resultData: "+ json );
                        String results = DeviceShowSaveData.getDataShow(json, BluetoothConstant.PW_01DEVICE_NAME);
                    } else {
                        tv_state.setText("测量结果异常");
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            Log.e(TAG, "出错了: "+ e.getMessage());
        }
    }

    /**
     * 搜索脉搏波4.0设备；设备名称包含BP开头的
     */
    private void scanMaiboboBle() {
        BleScanRuleConfig scanRuleConfig = new BleScanRuleConfig.Builder()
                .setScanTimeOut(15000)
                .build();
        BleManager.getInstance().initScanRule(scanRuleConfig);
        BleManager.getInstance().scan(new BleScanCallback() {
            @Override
            public void onScanStarted(boolean success) {
            }

            @Override
            public void onScanning(BleDevice bleDevice) {
                if (bleDevice.getName() != null && bleDevice.getName().startsWith("BP")) {
                    Log.e(TAG, "onScanning: " + bleDevice.getMac());
                    connMaiboboBleBle(bleDevice);
                }
            }

            @Override
            public void onScanFinished(List<BleDevice> scanResultList) {
            }
        });
    }

    private void connMaiboboBleBle(BleDevice bleDevice) {
        Log.e(TAG, "connectionBle: " + bleDevice.getMac());
        BleManager.getInstance().connect(bleDevice, new BleGattCallback() {
            @Override
            public void onStartConnect() {

            }

            @Override
            public void onConnectFail(BleDevice bleDevice, BleException exception) {
                ToastUtils.showShort("连接失败,请重新打开血压计设备");
                blueToothState.setText("连接失败");
                tv_state.setText("蓝牙连接失败请重新连接：");
                cancelProgressDialog();
                Log.e(TAG, "onConnectFail: " +  exception.toString());
            }

            @Override
            public void onConnectSuccess(final BleDevice bleDevice, BluetoothGatt gatt, int status) {
                //连接成功
                Log.e(TAG, "onConnectSuccess: ");
                showProgressDialog("等待接收脉搏波血压计数据");
                blueToothState.setText("蓝牙已连接");
                tv_state.setText("蓝牙已连接：\n        " + "等待返回结果");
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        getMaiboboNotify(bleDevice);
                    }
                },200);
            }

            @Override
            public void onDisConnected(boolean isActiveDisConnected, BleDevice device, BluetoothGatt gatt, int status) {
                blueToothState.setText("蓝牙已断开");
                Log.e(TAG, "onDisConnected: ");
            }
        });
    }

    private void getMaiboboNotify(final BleDevice bleDevice) {
        BleManager.getInstance().notify(bleDevice,
                BlueToothConstant.MAIBOBO_UUID_SERVICE.toString(),
                BlueToothConstant.MAIBOBO_UUID_NOTIFY.toString(),
                new BleNotifyCallback() {
                    @Override
                    public void onNotifySuccess() {
                        Log.e(TAG, "onNotifySuccess: ");
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                writeMaibobo(bleDevice, BlueToothConstant.CONN_DEVICE_COMMAND);
                            }
                        }, 1200);
                    }

                    @Override
                    public void onNotifyFailure(BleException exception) {
                        Log.e(TAG, "onNotifyFailure: " + exception.toString());
                    }

                    @Override
                    public void onCharacteristicChanged(byte[] data) {
                        //接收数据
                        resolveMaiboboData(bleDevice,data);
                    }
                });
    }

    private void writeMaibobo(final BleDevice bleDevice, final String command) {
        byte[] bytes = HexUtil.hexStringToBytes(command);
        BleManager.getInstance().write(bleDevice,
                BlueToothConstant.MAIBOBO_UUID_SERVICE.toString(),
                BlueToothConstant.MAIBOBO_UUID_WRITE.toString(), bytes, new BleWriteCallback() {
                    @Override
                    public void onWriteSuccess(int current, int total, byte[] justWrite) {
                        Log.e(TAG, "onWriteSuccess: ");
                    }

                    @Override
                    public void onWriteFailure(BleException exception) {
                        Log.e(TAG, "onWriteFailure: " + exception.toString());
                    }
                });
    }

    /**
     * 解析数据
     * @param data
     */
    private void resolveMaiboboData(BleDevice bleDevice,byte[] data) {
        String hexString = HexUtil.formatHexString(data);
        if ("aa80020301010001".equals(hexString)) {
            writeMaibobo(bleDevice, BlueToothConstant.START_DEVIC_COMMANDE);
            Log.e(TAG, "血压计返回连接指令: " + hexString);
        } else if ("aa80020301020002".equals(hexString)) {
            Log.e(TAG, "血压计返回启动测量指令: " + hexString);
        } else if ("aa80020301030003".equals(hexString)) {
            //血压计返回停止测量结果
            //断开连接
            blueToothState.setText("蓝牙已断开");
            disconnectMaibobo();
            Log.e(TAG, "血压计返回停止测量结果: 蓝牙主动断开连接");
        } else {
            String command = hexString.substring(10, 12);
            if ("06".equals(command)) {
                //最终结果
                int bloodUp = Integer.parseInt(hexString.substring(26, 30), 16);
                int bloodDown = Integer.parseInt(hexString.substring(30, 34), 16);
                int heart = Integer.parseInt(hexString.substring(34, 38), 16);
                Log.e(TAG, "高压: " + bloodUp + "  低压：" + bloodDown + "  心率：" + heart);
//                upLoadData(bloodUp,bloodDown,heart);
                saveMaiboboData(bloodUp,bloodDown,heart);
                writeMaibobo(bleDevice, BlueToothConstant.CLOSE_DEVICE_COMMAND);
            } else if ("05".equals(command)) {
                //实时数据 血压
                //aa80020801050000000045004b
//                int realBloodPressure = Math.abs(data[7] * 256 + data[10] ^ data[7]);
                int realBloodPressure = Integer.parseInt(hexString.substring(20,22),16);
                Log.e(TAG, "实时数据: " + realBloodPressure);
                Log.e(TAG, "notify: " + hexString);
            } else if ("07".equals(command)) {
                //测量错误
                ToastUtils.showShort("测量错误,请重新测量");
                cancelProgressDialog();
                Log.e(TAG, "测量错误: " + hexString);
            } else {
                Log.e(TAG, "notify: " + hexString);
            }
        }
    }

    private void saveMaiboboData(int bloodUp,int bloodDown,int heart) {
        //测量结果
        cancelProgressDialog();
        try{
            lay_result.setVisibility(View.VISIBLE);
            //收缩压、舒张压、心率
            String results = DeviceShowSaveData.getDataShow(bloodUp+";"+bloodDown+";"+heart+";",
                    BluetoothConstant.XUEYA_YE680A_YUYUE);
            Log.e("showData()3333", results + "*********************");
            tv_result.setText("测量结果：\n        " + results);
            tv_state.setText("获取测量结果成功");
            cancelProgressDialog();
            Log.e(TAG,"测量结果："+bloodUp+";"+bloodDown+";"+heart+";");
        }catch (Exception e){
            System.out.println("报异常了："+e.toString());
        }
    }

    private void disconnectMaibobo() {
        try {
            BleManager.getInstance().cancelScan();
        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            BleManager.getInstance().disconnectAllDevice();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    MyBleManager bleManager;

    private void bindingDevice() {
//        if (true) {
//            mDeviceName = "Health Scale";
//            LFPeopleGeneral bodyDataModel = new LFPeopleGeneral();
//            bodyDataModel.lfBMI = 23.5;
//            bodyDataModel.lfBMR = 24;
//            bodyDataModel.lfHeightCm = 175;
//            bodyDataModel.lfHeightCm = 175;
//            bodyDataModel.lfFatLevel = "3";
//            //保存体重
//            DeviceShowSaveData.saveHealthScale(bodyDataModel,"71");
//            return;
//        }

        int height = 0;
        String heightStr = et_height.getText().toString().trim();
        if (!TextUtils.isEmpty(heightStr)) {
            try {
                height = Integer.parseInt(heightStr);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
            if (height < 100 || height > 220) {
                ToastUtils.showLong("请输入100-220cm区间身高数据");
                return;
            }
        }

        showProgressDialog("正在测量体脂数据请稍后");
        mDeviceName = "Health Scale";
//        mDeviceName = "HeartRate Scale";
        bleManager = MyBleManager.shareInstance(getApplication());
        List<BleDeviceModel> deviceList = new ArrayList<>();
        ARCHIVE_BASEINFO userInfo = NovaApplication.getUserInfo();
        String sex = userInfo.getSEX();
        int age = GlobalConts.getAge(userInfo.getBIRTHDAY());
        BleEnum.BleSex sexEnum;
        if ("DM01-08_1".equals(sex)) {
            sexEnum = BleEnum.BleSex.Male;
        } else {
            sexEnum = BleEnum.BleSex.Female;
        }
        BleUserModel userModel = new BleUserModel(height, age,
                sexEnum, BleEnum.BleUnit.BLE_UNIT_KG, 0);

        /**
         *  开始扫描蓝牙
         *
         * @param isBinding 是否是绑定设备，第一次扫描或不指定扫描设备时设置false, 扫描指定设备设置为true
         * @param deviceList 指定扫描设备列表 isBinging设置为true该方法生效
         * @param userModel 用户基本信息，包括身高、年龄、性别、重量单位（需要秤支持）
         * @param protocoInterface 扫描数据回调类
         */
        bleManager.searchDevice(true, deviceList, userModel, new BleDataProtocoInterface() {
            /**
             * 过程数据回调
             * @param bodyDataModel
             */
            @Override
            public void progressData(final LFPeopleGeneral bodyDataModel) {
                //过程数据回调
                String weightStr = PPUtil.getWeight(userModel.unit, bodyDataModel.lfWeightKg);
                Log.e(TAG, "progressData: " +  weightStr);
                tv_result.setVisibility(View.VISIBLE);
                tv_result.setText("测量过程：\n        " + weightStr);
            }

            /**
             * 锁定数据回调 （由于用户可能没有传入正缺范围内的身高性别等信息或者秤重过程中的一些别的原因（穿鞋，没踩到电极片等），
             * 锁定数据中只有体重和BMI的数据。）
             * @param bodyDataModel 测量结果
             * @param deviceModel   设备信息
             * @param isHeartRating 是否开始测量心率，true开始测量 false不测量或测量结束
             */
            @Override
            public void lockedData(LFPeopleGeneral bodyDataModel, BleDeviceModel deviceModel, boolean isHeartRating) {
                if (!isHeartRating) {
                    cancelProgressDialog();
                    showHealthScale(bodyDataModel);
                    if (bleManager != null) {
                        bleManager.stopSearch();
                    }
                }
            }

            /**
             * 历史数据回调， 在测量完成后，支持离线数据的秤会回调，不支持不回调
             *
             * @param isEnd 结束标志
             * @param bodyDataModel 存储数据的对象
             * @param date 时间 yyyy-MM-dd HH:mm:ss
             */
            @Override
            public void historyData(boolean isEnd, LFPeopleGeneral bodyDataModel, String date) {

            }

            /**
             * 蓝牙设备信息回调,在lockedData（）执行时回调
             * @param deviceModel
             */
            @Override
            public void deviceInfo(BleDeviceModel deviceModel) {

            }
        });
    }

    /**
     * 保存轻加体脂秤测量结果
     * @param bodyDataModel 体脂数据
     */
    private void showHealthScale(LFPeopleGeneral bodyDataModel) {
        String weightStr = PPUtil.getWeight(BleEnum.BleUnit.BLE_UNIT_KG, bodyDataModel.lfWeightKg);
        Log.e(TAG, "lockedData: " + bodyDataModel.toString() );
        if (weightStr.contains("kg")) {
            weightStr = weightStr.replace("kg","");
        }
        lay_result.setVisibility(View.VISIBLE);
        lay_celiang.setVisibility(View.VISIBLE);
        //保存体重
        DeviceShowSaveData.saveHealthScale(bodyDataModel,weightStr);
        tv_result.setText("测量结果：\n        " + weightStr);
        tv_state.setText("获取测量结果成功");
    }


}
